"""
GT-OOP 学习管理系统(LMS) GUI模块
使用tkinter实现的图形用户界面
"""

import sys
import os
import tkinter as tk
from tkinter import IntVar, Text, Toplevel, ttk, messagebox, simpledialog, StringVar
import datetime
import json
from typing import Dict, List, Optional, Any, Tuple
from User_Management.data_persistence import load_all_data

# 添加项目根目录到系统路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# 导入LMS系统模块
from Progress_Tracking_CLI_DataPersistence.lms_main import LMS
from User_Management.user_classes import User, Student, Teacher, Administrator
from Course_Management_and_Enrollment.course_task_classes import Course
from Progress_Tracking_CLI_DataPersistence.config import SYSTEM_NAME, SYSTEM_VERSION

class GT_OOP_LMS_GUI:
    """GT-OOP学习管理系统的主GUI类"""
    def __init__(self):
        # 初始化主窗口
        self.root = tk.Tk()
        self.root.title(f"{SYSTEM_NAME} v{SYSTEM_VERSION}")
        self.root.geometry("1200x800")
        self.root.minsize(1024, 768)
        self.root.configure(bg="#f0f0f0")
        
        # 初始化LMS系统
        self.lms = LMS()
        self.current_user = None
        
        # 设置样式主题
        self._setup_styles()
        
        # 显示登录界面
        self.show_login_screen()

        self._setup_auto_save()

        self.root.protocol("WM_DELETE_WINDOW", self._on_closing)
        
        # 启动主循环
        self.root.mainloop()


    def _on_closing(self):
        """窗口关闭时的处理"""
        try:
            # 只有在有实际更改时才保存数据
            # 这需要与LMS类中的数据变更检测机制配合使用
            if hasattr(self.lms, 'data_has_changed') and self.lms.data_has_changed:
                if hasattr(self.lms, 'save_data'):
                    self.lms.save_data(force=True)
            self.root.destroy()
        except Exception as e:
            print(f"关闭时保存数据出错: {str(e)}")
            self.root.destroy()
        
    def _setup_styles(self):
        """设置UI样式"""
        self.style = ttk.Style()
        
        # 设置主题
        try:
            self.style.theme_use("clam")
        except:
            pass  # 如果主题不可用则使用默认主题
        
        # 定义颜色方案
        self.colors = {
            "primary": "#4a6fa5",  # 蓝色作为主色调
            "secondary": "#e74c3c",  # 红色作为次色调
            "accent": "#27ae60",  # 绿色作为强调色
            "background": "#f0f0f0",  # 浅灰色背景
            "card_bg": "#ffffff",  # 卡片背景色
            "text": "#333333",  # 文本颜色
            "text_light": "#777777",  # 浅色文本
            "border": "#dddddd"  # 边框颜色
        }
        
        # 设置按钮样式
        self.style.configure(
            "Primary.TButton", 
            font=(".AppleSystemUIFont", 10, "bold"),
            foreground="white",
            background=self.colors["primary"],
            padding=(10, 5)
        )
        
        self.style.configure(
            "Secondary.TButton", 
            font=(".AppleSystemUIFont", 10),
            foreground="white",
            background=self.colors["secondary"],
            padding=(10, 5)
        )
        
        self.style.configure(
            "Accent.TButton", 
            font=(".AppleSystemUIFont", 10),
            foreground="white",
            background=self.colors["accent"],
            padding=(10, 5)
        )
        
        # 设置标签样式
        self.style.configure(
            "Heading.TLabel", 
            font=(".AppleSystemUIFont", 16, "bold"),
            foreground=self.colors["primary"],
            background=self.colors["background"],
            padding=(5, 10)
        )
        
        self.style.configure(
            "Subheading.TLabel", 
            font=(".AppleSystemUIFont", 12, "bold"),
            foreground=self.colors["text"],
            background=self.colors["background"],
            padding=(5, 5)
        )
        
        # 设置框架样式
        self.style.configure(
            "Card.TFrame", 
            background=self.colors["card_bg"],
            relief="solid",
            borderwidth=1,
            bordercolor=self.colors["border"]
        )
        
        # 设置输入框样式
        self.style.configure(
            "TEntry", 
            font=(".AppleSystemUIFont", 10),
            padding=(5, 3)
        )
        
        # 设置Treeview样式
        self.style.configure(
            "Custom.Treeview",
            font=(".AppleSystemUIFont", 10),
            background=self.colors["card_bg"],
            foreground=self.colors["text"],
            rowheight=25,
            fieldbackground=self.colors["card_bg"]
        )
        
        self.style.configure(
            "Custom.Treeview.Heading",
            font=(".AppleSystemUIFont", 10, "bold"),
            background=self.colors["primary"],
            foreground="white",
            padding=(10, 5)
        )
        
    def _clear_window(self):
        """清空当前窗口中的所有组件"""
        for widget in self.root.winfo_children():
            widget.destroy()
    
    def show_login_screen(self):
        """显示登录界面"""
        # 清空当前窗口
        self._clear_window()
        
        # 创建登录框架
        login_frame = ttk.Frame(self.root, padding=20, style="Card.TFrame")
        login_frame.place(relx=0.5, rely=0.5, anchor="center", width=400, height=450)
        
        # 创建标题
        title_label = ttk.Label(login_frame, text=SYSTEM_NAME, style="Heading.TLabel")
        title_label.pack(pady=20)
        
        version_label = ttk.Label(login_frame, text=f"version {SYSTEM_VERSION}", foreground=self.colors["text_light"])
        version_label.pack(pady=(0, 20))
        
        # 创建登录表单
        form_frame = ttk.Frame(login_frame)
        form_frame.pack(fill="x", padx=20)
        
        # 用户名
        username_label = ttk.Label(form_frame, text="username:")
        username_label.pack(anchor="w", pady=(0, 5))
        self.username_entry = ttk.Entry(form_frame)
        self.username_entry.pack(fill="x", pady=(0, 15))
        self.username_entry.focus()
        
        # 密码
        password_label = ttk.Label(form_frame, text="password:")
        password_label.pack(anchor="w", pady=(0, 5))
        self.password_entry = ttk.Entry(form_frame, show="*")
        self.password_entry.pack(fill="x", pady=(0, 5))

        # 添加密码可见性切换复选框
        self.show_password_var = tk.BooleanVar()
        show_password_checkbox = ttk.Checkbutton(
            form_frame, 
            text="show password", 
            variable=self.show_password_var, 
            command=self.toggle_password_visibility
        )
        show_password_checkbox.pack(anchor="w", pady=(0, 15))

        # 登录按钮
        login_button = ttk.Button(form_frame, text="login", style="Primary.TButton", command=self._handle_login)
        login_button.pack(fill="x", pady=(0, 10))
        
        # 注册按钮
        register_button = ttk.Button(form_frame, text="register", style="Accent.TButton", command=self._show_register_screen)
        register_button.pack(fill="x", pady=(0, 10))
        
        # 退出按钮
        exit_button = ttk.Button(form_frame, text="logout", style="Secondary.TButton", command=self.root.quit)
        exit_button.pack(fill="x")
        
        # 绑定回车键到登录按钮
        self.root.bind("<Return>", lambda event: self._handle_login())

    def toggle_password_visibility(self):
        """切换密码可见性"""
        if self.show_password_var.get():
            self.password_entry.config(show="")
        else:
            self.password_entry.config(show="*")
    
    def _show_register_screen(self):
        """显示注册界面"""
        # 创建注册对话框
        register_window = tk.Toplevel(self.root)
        register_window.title("register")
        register_window.geometry("400x480")
        register_window.configure(bg=self.colors["background"])
        register_window.resizable(False, False)
        register_window.transient(self.root)
        register_window.grab_set()
        
        # 居中显示
        register_window.update_idletasks()
        width = register_window.winfo_width()
        height = register_window.winfo_height()
        x = (register_window.winfo_screenwidth() // 2) - (width // 2)
        y = (register_window.winfo_screenheight() // 2) - (height // 2)
        register_window.geometry('{}x{}+{}+{}'.format(width, height, x, y))
        
        # 创建注册表单
        form_frame = ttk.Frame(register_window, padding=20)
        form_frame.pack(fill="both", expand=True)
        
        # 标题
        title_label = ttk.Label(form_frame, text="register", style="Subheading.TLabel")
        title_label.pack(pady=(0, 20))
        
        # 用户名
        username_label = ttk.Label(form_frame, text="username:")
        username_label.pack(anchor="w", pady=(0, 5))
        username_entry = ttk.Entry(form_frame)
        username_entry.pack(fill="x", pady=(0, 10))
        
        # 密码
        password_label = ttk.Label(form_frame, text="password:")
        password_label.pack(anchor="w", pady=(0, 5))
        password_entry = ttk.Entry(form_frame, show="*")
        password_entry.pack(fill="x", pady=(0, 10))
        
        # 确认密码
        confirm_label = ttk.Label(form_frame, text="confirm password:")
        confirm_label.pack(anchor="w", pady=(0, 5))
        confirm_entry = ttk.Entry(form_frame, show="*")
        confirm_entry.pack(fill="x", pady=(0, 10))
        
        # 邮箱
        email_label = ttk.Label(form_frame, text="email:")
        email_label.pack(anchor="w", pady=(0, 5))
        email_entry = ttk.Entry(form_frame)
        email_entry.pack(fill="x", pady=(0, 15))
        
        # 角色选择
        role_label = ttk.Label(form_frame, text="role:")
        role_label.pack(anchor="w", pady=(0, 5))
        role_var = tk.StringVar()
        role_combo = ttk.Combobox(form_frame, textvariable=role_var, state="readonly")
        role_combo['values'] = ("student", "teacher", "admin")
        role_combo.current(0)  # 默认选择学生
        role_combo.pack(fill="x", pady=(0, 15))
        
        # 按钮框架
        buttons_frame = ttk.Frame(form_frame)
        buttons_frame.pack(fill="x", pady=(10, 0))
        
        # 注册按钮
        def handle_register():
            """处理注册逻辑"""
            username = username_entry.get().strip()
            password = password_entry.get().strip()
            confirm = confirm_entry.get().strip()
            email = email_entry.get().strip()
            role_text = role_var.get()
            
            # 验证输入
            if not all([username, password, confirm, email]):
                messagebox.showerror("register error", "Please fill in all required fields.")
                return
            
            if password != confirm:
                messagebox.showerror("register error", "Passwords do not match.")
                return
            
            # 映射角色文本到系统角色
            role_mapping = {"student": "student", "teacher": "teacher", "admin": "admin"}
            role = role_mapping.get(role_text, "student")
            
            try:
                new_user = User.register(username, password, email, role)
                
                # 确保新用户被添加到系统所有相关列表
                if new_user not in self.lms.users:
                    self.lms.users.append(new_user)
                    
                    if isinstance(new_user, Student) and new_user not in self.lms.students:
                        self.lms.students.append(new_user)
                    elif isinstance(new_user, Teacher) and new_user not in self.lms.teachers:
                        self.lms.teachers.append(new_user)
                    elif isinstance(new_user, Administrator) and hasattr(self.lms, 'administrators') and new_user not in self.lms.administrators:
                        self.lms.administrators.append(new_user)
                
                # 使用增量保存用户方法,避免覆盖现有数据
                user_data = new_user.to_dict()
                if hasattr(self.lms, 'data_persistence'):
                    self.lms.data_persistence.add_user(user_data)
                
                # 标记数据已变更,确保系统状态更新
                self.lms.mark_data_changed()
                
                messagebox.showinfo("register success", f"User '{username}' registered successfully!")
                register_window.destroy()
            except Exception as e:
                messagebox.showerror("register error", f"Registration failed: {str(e)}")
        
        register_button = ttk.Button(buttons_frame, text="register", style="Primary.TButton", command=handle_register)
        register_button.pack(side="left", fill="x", expand=True, padx=(0, 5))
        
        # 取消按钮
        cancel_button = ttk.Button(buttons_frame, text="cancel", style="Secondary.TButton", command=register_window.destroy)
        cancel_button.pack(side="right", fill="x", expand=True, padx=(5, 0))

    def show_user_management(self):
        """显示用户管理界面"""
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="user management", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建操作按钮框架
        actions_frame = ttk.Frame(self.content_panel)
        actions_frame.pack(fill="x", pady=10, padx=10)
        
        # 添加用户按钮
        add_user_button = ttk.Button(actions_frame, text="add user", style="Accent.TButton", 
                                    command=self._show_add_user_dialog)
        add_user_button.pack(side="left", padx=5)

        # 添加删除用户按钮
        delete_user_button = ttk.Button(actions_frame, text="delete user", style="Secondary.TButton", 
                                       command=self._delete_selected_user)
        delete_user_button.pack(side="left", padx=5)
        
        # 创建用户表格框架
        table_frame = ttk.Frame(self.content_panel)
        table_frame.pack(fill="both", expand=True, pady=10, padx=10)
        
        # 创建滚动条
        scrollbar = ttk.Scrollbar(table_frame)
        scrollbar.pack(side="right", fill="y")
        
        # 创建用户表格
        self.users_tree = ttk.Treeview(table_frame, columns=("user_id", "username", "role", "email"), 
                                      show="headings", yscrollcommand=scrollbar.set, style="Custom.Treeview")
        
        # 设置列标题
        self.users_tree.heading("user_id", text="user id")
        self.users_tree.heading("username", text="username")
        self.users_tree.heading("role", text="role")
        self.users_tree.heading("email", text="email")
        
        # 设置列宽
        self.users_tree.column("user_id", width=100)
        self.users_tree.column("username", width=100)
        self.users_tree.column("role", width=80)
        self.users_tree.column("email", width=200)
        
        # 绑定滚动条
        scrollbar.config(command=self.users_tree.yview)
        
        # 显示表格
        self.users_tree.pack(fill="both", expand=True)
        
        # 加载用户数据
        self._load_users_data()

    def _delete_selected_user(self):
        """删除选中的用户"""
        # 获取选中的用户
        selected_item = self.users_tree.selection()
        if not selected_item:
            messagebox.showinfo("info", "please select a user to delete")
            return
        
        # 获取用户信息
        item = self.users_tree.item(selected_item)
        user_id = item["values"][0]  # 用户ID在第一列
        username = item["values"][1]  # 用户名在第二列
        
        # 确认删除
        if messagebox.askyesno("confirm delete", f"are you sure to delete user '{username}' (ID: {user_id})?\nnote: deletion is irreversible."):
            try:
                # 调用Administrator的delete_user方法
                if hasattr(self.current_user, 'delete_user'):
                    if self.current_user.delete_user(user_id):
                        # 删除成功后刷新用户列表并保存数据
                        self.lms.mark_data_changed()
                        self.lms.save_data(force=True)
                        self._load_users_data()
                        messagebox.showinfo("success", f"user '{username}' has been successfully deleted")
                    else:
                        messagebox.showerror("error", "deletion failed")
                else:
                    messagebox.showerror("error", "current user does not have permission to delete users")
            except Exception as e:
                messagebox.showerror("error", f"deletion failed: {str(e)}")
    
    def _show_add_user_dialog(self):
        """显示添加用户对话框"""
        # 创建对话框
        dialog = tk.Toplevel(self.root)
        dialog.title("add user")
        dialog.geometry("400x400")
        dialog.configure(bg=self.colors["background"])
        dialog.resizable(False, False)
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        width = dialog.winfo_width()
        height = dialog.winfo_height()
        x = (dialog.winfo_screenwidth() // 2) - (width // 2)
        y = (dialog.winfo_screenheight() // 2) - (height // 2)
        dialog.geometry(f"{width}x{height}+{x}+{y}")
        
        # 创建表单
        form_frame = ttk.Frame(dialog, padding=20)
        form_frame.pack(fill="both", expand=True)
        
        # 用户名
        username_label = ttk.Label(form_frame, text="username:")
        username_label.pack(anchor="w", pady=(0, 5))
        username_entry = ttk.Entry(form_frame)
        username_entry.pack(fill="x", pady=(0, 10))
        
        # 密码
        password_label = ttk.Label(form_frame, text="password:")
        password_label.pack(anchor="w", pady=(0, 5))
        password_entry = ttk.Entry(form_frame, show="*")
        password_entry.pack(fill="x", pady=(0, 10))
        
        # 邮箱
        email_label = ttk.Label(form_frame, text="email:")
        email_label.pack(anchor="w", pady=(0, 5))
        email_entry = ttk.Entry(form_frame)
        email_entry.pack(fill="x", pady=(0, 10))
        
        # 角色选择
        role_label = ttk.Label(form_frame, text="user role:")
        role_label.pack(anchor="w", pady=(0, 5))
        role_var = tk.StringVar()
        role_combo = ttk.Combobox(form_frame, textvariable=role_var, state="readonly")
        role_combo['values'] = ("student", "teacher", "admin")
        role_combo.current(0)  # 默认选择学生
        role_combo.pack(fill="x", pady=(0, 15))
        
        # 按钮框架
        buttons_frame = ttk.Frame(form_frame)
        buttons_frame.pack(fill="x", pady=(10, 0))
        
        # 添加按钮
        def handle_add():
            username = username_entry.get().strip()
            password = password_entry.get().strip()
            email = email_entry.get().strip()
            role_text = role_var.get()
            
            # 验证输入
            if not all([username, password, email]):
                messagebox.showerror("error", "please fill in all required fields")
                return
            
            # 映射角色文本到系统角色
            role_mapping = {"student": "student", "teacher": "teacher", "admin": "admin"}
            role = role_mapping.get(role_text, "student")
            
            try:
                # 调用User类的register方法
                new_user = User.register(username, password, email, role)
                
                if new_user:
                    messagebox.showinfo("success", f"user '{username}' has been successfully added!")
                    self.lms.save_user_incrementally(new_user)
                    self._load_users_data()  # 刷新用户列表
                    dialog.destroy()
                else:
                    messagebox.showerror("error", "registration failed, please try again")
            except Exception as e:
                messagebox.showerror("error", f"registration failed: {str(e)}")
        
        # 添加按钮
        add_button = ttk.Button(buttons_frame, text="add", style="Accent.TButton", command=handle_add)
        add_button.pack(side="left", fill="x", expand=True, padx=(0, 5))
        
        # 取消按钮
        cancel_button = ttk.Button(buttons_frame, text="cancel", command=dialog.destroy)
        cancel_button.pack(side="right", fill="x", expand=True, padx=(5, 0))
    
    def _load_users_data(self):
        """加载用户数据到表格"""
        # 清空表格
        for item in self.users_tree.get_children():
            self.users_tree.delete(item)
        
        # 获取所有用户
        if hasattr(User, "all_users"):
            users = User.all_users()
            
            # 角色映射
            role_mapping = {"student": "student", "teacher": "teacher", "admin": "admin"}
            
            # 添加用户到表格
            for user in users:
                role_text = role_mapping.get(user.role, "unknown")
                self.users_tree.insert("", "end", values=(user.user_id, user.username, role_text, user.email))

    

    def _handle_login(self):
        """处理登录逻辑"""
        username = self.username_entry.get().strip()
        password = self.password_entry.get().strip()
        
        if not all([username, password]):
            messagebox.showerror("error", "please enter username and password")
            return
        
        try:
            # 初始化系统
            if self.lms.system_status == "uninitialized":
                self.lms.initialize_system()
                
            # 确保User类已正确加载
            if not hasattr(User, "all_users"):
                messagebox.showerror("error", "user module not loaded correctly")
                return
            
            # 遍历所有用户,尝试登录
            users = User.all_users()
            for user in users:
                if user.login(username, password):
                    self.current_user = user
                    self.lms.current_user = user
                    
                    # 为管理员初始化用户和课程列表
                    if isinstance(user, Administrator):
                        user.system_users = users
                        if hasattr(Course, "all_courses"):
                            user.all_courses = Course.all_courses()
                    
                    messagebox.showinfo("success", f"welcome back,{username}!")
                    self.show_main_dashboard()
                    return
            
            # 如果没有找到匹配的用户
            messagebox.showerror("error", "username or password incorrect")
            
        except Exception as e:
            messagebox.showerror("error", f"login process failed: {str(e)}")

    def _handle_logout(self):
        """处理登出逻辑"""
        self.current_user = None
        self.lms.current_user = None
        self.show_login_screen()
        messagebox.showinfo("logout", "you have successfully logged out")
    
    def show_main_dashboard(self):
        """显示主仪表盘"""
        # 清空当前窗口
        self._clear_window()
        
        # 创建顶部导航栏
        top_bar = ttk.Frame(self.root, height=50, style="Card.TFrame")
        top_bar.pack(fill="x", side="top", pady=10, padx=10)
        
        # 系统标题
        title_label = ttk.Label(top_bar, text=f"{SYSTEM_NAME}", style="Subheading.TLabel")
        title_label.pack(side="left", padx=10)
        
        # 用户信息
        user_info = ttk.Label(
            top_bar, 
            text=f"user: {self.current_user.username} | role: {self._get_role_text()}",
            foreground=self.colors["text_light"]
        )
        user_info.pack(side="right", padx=10)
        
        # 注销按钮
        logout_button = ttk.Button(top_bar, text="logout", style="Secondary.TButton", command=self._handle_logout)
        logout_button.pack(side="right", padx=10)
        
        # 创建主内容区
        main_content = ttk.Frame(self.root, padding=10)
        main_content.pack(fill="both", expand=True)
        
        # 创建侧边栏
        sidebar = ttk.Frame(main_content, width=200, style="Card.TFrame")
        sidebar.pack(side="left", fill="y", padx=(0, 10))
        
        # 创建内容面板
        self.content_panel = ttk.Frame(main_content, style="Card.TFrame")
        self.content_panel.pack(side="right", fill="both", expand=True)
        
        # 根据用户角色添加侧边栏菜单项
        if isinstance(self.current_user, Student):
            self._add_student_menu(sidebar)
        elif isinstance(self.current_user, Teacher):
            self._add_teacher_menu(sidebar)
        elif isinstance(self.current_user, Administrator):
            self._add_admin_menu(sidebar)
        
        # 默认显示仪表盘
        self.show_dashboard()
    
    def _get_role_text(self):
        """获取用户角色的中文文本"""
        if isinstance(self.current_user, Student):
            return "student"
        elif isinstance(self.current_user, Teacher):
            return "teacher"
        elif isinstance(self.current_user, Administrator):
            return "admin"
        return "unknown"
    
    def _add_student_menu(self, parent):
        """添加学生菜单"""
        menu_items = [
            ("dashboard", self.show_dashboard),
            ("my courses", self.show_my_courses),
            ("grade query", self.show_grades),
            ("my assignments", self.show_my_assignments),  # 新增选项
            ("enroll courses", self.show_enroll_courses),
            ("profile", self.show_profile)
        ]
        
        self._add_menu_items(parent, menu_items)
    
    def _add_teacher_menu(self, parent):
        """添加教师菜单"""
        menu_items = [
            ("dashboard", self.show_dashboard),
            ("my courses", self.show_managed_courses),
            ("class roster", self.show_class_roster),
            ("assignment management", self.show_assignment_management),
            ("grade assignment", self.show_grade_assignment),
            ("profile", self.show_profile)
        ]
        
        self._add_menu_items(parent, menu_items)

    def show_assignment_management(self):
        """显示作业管理界面"""
        self._clear_content_panel()
        
        # 创建标题标签
        title_frame = ttk.Frame(self.content_panel)
        title_frame.pack(fill="x", pady=10, padx=10)
        
        title_label = ttk.Label(title_frame, text="assignment management", font=("SimHei", 18, "bold"))
        title_label.pack(side="left")
        
        # 添加创建作业按钮
        create_assignment_btn = ttk.Button(title_frame, text="create new assignment", 
                                          command=self._show_create_assignment_dialog)
        create_assignment_btn.pack(side="right", padx=5)
        
        # 创建作业列表框架
        assignments_frame = ttk.LabelFrame(self.content_panel, text="my assignments")
        assignments_frame.pack(fill="both", expand=True, pady=10, padx=10)
        
        # 创建滚动条
        scrollbar = ttk.Scrollbar(assignments_frame)
        scrollbar.pack(side="right", fill="y")
        
        # 创建作业树视图
        columns = ("course", "title", "due_date", "status", "actions")
        self.assignments_tree = ttk.Treeview(assignments_frame, columns=columns, show="headings", yscrollcommand=scrollbar.set)
        
        # 定义列宽和标题
        self.assignments_tree.heading("course", text="course")
        self.assignments_tree.heading("title", text="title")
        self.assignments_tree.heading("due_date", text="due date")
        self.assignments_tree.heading("status", text="status")
        self.assignments_tree.heading("actions", text="actions")
        
        self.assignments_tree.column("course", width=150)
        self.assignments_tree.column("title", width=250)
        self.assignments_tree.column("due_date", width=120)
        self.assignments_tree.column("status", width=100)
        self.assignments_tree.column("actions", width=120)
        
        self.assignments_tree.pack(fill="both", expand=True, padx=10, pady=10)
        scrollbar.config(command=self.assignments_tree.yview)
        
        # 加载作业数据
        self._load_assignments_data()
        
    def _load_assignments_data(self):
        """加载作业数据并在Treeview中显示"""
        # 清空现有的Treeview数据
        for item in self.assignments_tree.get_children():
            self.assignments_tree.delete(item)
        
        # 检查当前用户是否为教师
        if hasattr(self.current_user, 'managed_courses') and self.current_user.managed_courses:
            # 遍历所有管理的课程
            for course in self.current_user.managed_courses:
                # 检查课程是否有作业
                if hasattr(course, 'course_assignments') and course.course_assignments:
                    for assignment in course.course_assignments:
                        # 确保作业对象有必要的属性
                        if hasattr(assignment, 'title') and hasattr(assignment, 'due_date'):
                            # 格式化截止日期
                            due_date_str = ""
                            if isinstance(assignment.due_date, str):
                                # 尝试解析字符串格式的日期
                                try:
                                    from datetime import datetime
                                    date_obj = datetime.fromisoformat(assignment.due_date)
                                    due_date_str = date_obj.strftime("%Y-%m-%d %H:%M")
                                except:
                                    due_date_str = assignment.due_date
                            elif hasattr(assignment.due_date, 'strftime'):
                                due_date_str = assignment.due_date.strftime("%Y-%m-%d %H:%M")
                            else:
                                due_date_str = str(assignment.due_date)
                            
                            # 添加到Treeview
                            item_id = self.assignments_tree.insert("", "end", values=(course.course_name, assignment.title, due_date_str, "未提交", "编辑 | 删除"))
        
        # 添加选择事件绑定
        self.assignments_tree.bind("<<TreeviewSelect>>", self._on_assignment_select)
        
        # 添加操作按钮面板
        self._create_action_buttons()

        
    def _create_action_buttons(self):
        # 检查是否已存在操作按钮面板
        for widget in self.content_panel.winfo_children():
            if isinstance(widget, ttk.Frame) and hasattr(widget, "_is_action_panel"):
                widget.destroy()
                
        # 创建操作按钮面板
        action_panel = ttk.Frame(self.content_panel, padding=10)
        action_panel._is_action_panel = True  # 标记为操作面板
        action_panel.pack(fill="x", pady=(0, 10), padx=10)
        
        # 创建操作按钮
        self.edit_button = ttk.Button(action_panel, text="edit assignment", state="disabled", 
                                     command=self._on_edit_assignment)
        self.edit_button.pack(side="left", padx=5)
        
        self.delete_button = ttk.Button(action_panel, text="delete assignment", state="disabled", 
                                       command=self._on_delete_assignment)
        self.delete_button.pack(side="left", padx=5)
        
    def _on_assignment_select(self, event):
        """处理作业选择事件"""
        selection = self.assignments_tree.selection()
        if selection:
            # 启用操作按钮
            self.edit_button.config(state="normal")
            self.delete_button.config(state="normal")
        else:
            # 禁用操作按钮
            self.edit_button.config(state="disabled")
            self.delete_button.config(state="disabled")
            
    def _on_edit_assignment(self):
        """处理编辑作业事件"""
        selection = self.assignments_tree.selection()
        if selection:
            item = self.assignments_tree.item(selection[0])
            course = item["values"][0]
            title = item["values"][1]
            self._show_edit_assignment_dialog(course, title)
            
    def _on_delete_assignment(self):
        """处理删除作业事件"""
        selection = self.assignments_tree.selection()
        if selection:
            self._delete_assignment(selection[0])
        
    def _show_create_assignment_dialog(self):
        """显示创建作业对话框"""
        dialog = Toplevel(self.root)
        dialog.title("create new assignment")
        dialog.geometry("500x400")
        dialog.resizable(False, False)
        
        # 居中显示
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 课程选择 - 动态获取当前教师管理的课程
        ttk.Label(dialog, text="select course:").grid(row=0, column=0, padx=10, pady=10, sticky="w")
        course_var = StringVar()
        course_combo = ttk.Combobox(dialog, textvariable=course_var, width=30)
        
        # 获取当前教师管理的课程列表
        course_options = []
        if hasattr(self.current_user, 'managed_courses'):
            # 确保managed_courses不为None且是列表
            if self.current_user.managed_courses and isinstance(self.current_user.managed_courses, list):
                course_options = [course.course_name for course in self.current_user.managed_courses if hasattr(course, 'course_name')]
        
        if not course_options:
            messagebox.showinfo("info", "you don't have any courses to manage")
            dialog.destroy()
            return
            
        course_combo['values'] = course_options
        course_combo.current(0)  # 默认选择第一个课程
        course_combo.configure(state='readonly')  # 设置为只读,防止手动输入
        course_combo.grid(row=0, column=1, padx=10, pady=10, sticky="w")
        
        # 作业标题
        ttk.Label(dialog, text="assignment title:").grid(row=1, column=0, padx=10, pady=10, sticky="w")
        title_entry = ttk.Entry(dialog, width=30)
        title_entry.grid(row=1, column=1, padx=10, pady=10, sticky="w")
        
        # 截止日期 - 使用日期选择器替代文本输入框
        ttk.Label(dialog, text="due date:").grid(row=2, column=0, padx=10, pady=10, sticky="w")
        
        # 导入日期选择器组件
        from tkcalendar import DateEntry
        from datetime import datetime, timedelta
        
        # 创建日期选择器
        date_frame = ttk.Frame(dialog)
        date_frame.grid(row=2, column=1, padx=10, pady=10, sticky="w")
        
        # 日期选择
        date_entry = DateEntry(date_frame, width=12, background='darkblue',
                              foreground='white', borderwidth=2, year=datetime.now().year)
        date_entry.grid(row=0, column=0, padx=5)
        
        # 时间选择 - 添加小时和分钟选择框
        ttk.Label(date_frame, text="time: ").grid(row=0, column=1, padx=5)
        
        # 小时选择
        hour_var = IntVar(value=datetime.now().hour)
        hour_spinbox = ttk.Spinbox(date_frame, from_=0, to=23, width=3, textvariable=hour_var)
        hour_spinbox.grid(row=0, column=2, padx=5)
        
        ttk.Label(date_frame, text=":").grid(row=0, column=3)
        
        # 分钟选择
        minute_var = IntVar(value=0)
        minute_spinbox = ttk.Spinbox(date_frame, from_=0, to=59, width=3, textvariable=minute_var)
        minute_spinbox.grid(row=0, column=4, padx=5)
        
        # 作业描述
        ttk.Label(dialog, text="assignment description:").grid(row=3, column=0, padx=10, pady=10, sticky="nw")
        description_text = Text(dialog, width=40, height=10)
        description_text.grid(row=3, column=1, padx=10, pady=10, sticky="nw")
        
        # 按钮框架
        btn_frame = ttk.Frame(dialog)
        btn_frame.grid(row=4, column=0, columnspan=2, pady=20)
        
        # 创建按钮 - 修改回调函数以处理日期选择器的值
        def process_assignment_creation():
            # 获取日期和时间
            selected_date = date_entry.get_date()
            selected_hour = hour_var.get()
            selected_minute = minute_var.get()
            
            # 组合成完整的日期时间
            due_date_str = datetime(selected_date.year, selected_date.month, selected_date.day, 
                                   selected_hour, selected_minute).strftime("%Y-%m-%d %H:%M")
            
            # 调用原始的创建作业方法
            self._create_assignment(
                dialog, course_var.get(), title_entry.get(), 
                due_date_str, description_text.get("1.0", "end-1c")
            )

            self.lms.mark_data_changed()
            self.lms.save_data()  
            
        create_btn = ttk.Button(btn_frame, text="create", width=10, command=process_assignment_creation)
        create_btn.pack(side="left", padx=10)
        
        # 取消按钮
        cancel_btn = ttk.Button(btn_frame, text="cancel", width=10, command=dialog.destroy)
        cancel_btn.pack(side="left", padx=10)
    
        
    def _create_assignment(self, dialog, course_name, title, due_date, description):
        """创建新作业"""
        # 验证输入
        if not course_name or not title or not due_date:
            messagebox.showerror("error", "please fill in all required fields")
            return
            
        try:
            # 查找对应的课程对象
            selected_course = None
            available_courses = []
            
            # 确保managed_courses存在且是有效的列表
            if hasattr(self.current_user, 'managed_courses') and self.current_user.managed_courses:
                for course in self.current_user.managed_courses:
                    if hasattr(course, 'course_name'):
                        available_courses.append(course.course_name)
                        if course.course_name == course_name:
                            selected_course = course
                            break
            
            # 如果仍未找到,提供更详细的错误信息
            if not selected_course:
                error_msg = f"course '{course_name}' not found.\n\n"
                if available_courses:
                    error_msg += f"your managed courses are: {', '.join(available_courses)}\n"
                    error_msg += "\nplease select a course from the dropdown list, don't type manually."
                else:
                    error_msg += "you have no managed courses, please create a course first."
                messagebox.showerror("error", error_msg)    
                return
                
            # 调用Teacher的create_assignment方法
            assignment_info = {
                "title": title,
                "content": description,
                "due_date": due_date,
                "format": "text"
            }
            
            # 创建作业 - 修复变量名,使用selected_course而不是course
            assignment = self.current_user.create_assignment(selected_course, assignment_info)
        
            if assignment:
                messagebox.showinfo("success", f"assignment '{assignment.title}' created successfully!\nautomatically linked to {len(selected_course.enrolled_students)} students in this course.")
                # 刷新作业列表
                self._load_assignments_data()
                # 强制保存数据,确保作业被保存
                if hasattr(self, 'lms') and hasattr(self.lms, 'save_data'):
                    try:
                        self.lms.save_data(force=True)
                    except Exception as e:
                        messagebox.showerror("error", f"error saving data: {str(e)}")
            else:
                messagebox.showerror("error", "assignment creation failed!")
        except Exception as e:
            messagebox.showerror("error", f"error creating assignment: {str(e)}")

        
    def _show_edit_assignment_dialog(self, course_name, assignment_title):
        """显示编辑作业对话框"""
        try:
            # 查找对应的课程和作业对象
            selected_course = None
            for course in self.current_user.managed_courses:
                if course.course_name.lower() == course_name.lower():
                    selected_course = course
                    break
                    
            if not selected_course:
                messagebox.showerror("error", f"course '{course_name}' not found.")
                return
                
            selected_assignment = None
            for assignment in selected_course.course_assignments:
                if assignment.title.lower() == assignment_title.lower():
                    selected_assignment = assignment
                    break
                    
            if not selected_assignment:
                # 显示该课程下的所有作业
                available_assignments = [assignment.title for assignment in selected_course.course_assignments]
                messagebox.showerror("error", 
                                    f"assignment '{assignment_title}' not found.\n\n" +
                                    f"available assignments in this course: {', '.join(available_assignments) if available_assignments else 'none'}")
                return
                
            # 创建编辑对话框
            dialog = Toplevel(self.root)
            dialog.title("edit assignment")
            dialog.geometry("500x400")
            dialog.resizable(False, False)
            
            # 居中显示
            dialog.transient(self.root)
            dialog.grab_set()
            
            # 作业标题
            ttk.Label(dialog, text="assignment title:").grid(row=0, column=0, padx=10, pady=10, sticky="w")
            title_entry = ttk.Entry(dialog, width=30)
            title_entry.grid(row=0, column=1, padx=10, pady=10, sticky="w")
            title_entry.insert(0, selected_assignment.title)
            
            # 截止日期 - 使用日期选择器替代文本输入框
            ttk.Label(dialog, text="due date:").grid(row=1, column=0, padx=10, pady=10, sticky="w")
            
            # 导入日期选择器组件
            from tkcalendar import DateEntry
            from datetime import datetime
            
            # 创建日期选择器
            date_frame = ttk.Frame(dialog)
            date_frame.grid(row=1, column=1, padx=10, pady=10, sticky="w")
            
            # 日期选择 - 设置初始日期为作业的截止日期
            due_date = selected_assignment.due_date
            date_entry = DateEntry(date_frame, width=12, background='darkblue',
                                  foreground='white', borderwidth=2, 
                                  year=due_date.year, month=due_date.month, day=due_date.day)
            date_entry.grid(row=0, column=0, padx=5)
            
            # 时间选择
            ttk.Label(date_frame, text="time: ").grid(row=0, column=1, padx=5)
            
            # 小时选择
            hour_var = IntVar(value=due_date.hour)
            hour_spinbox = ttk.Spinbox(date_frame, from_=0, to=23, width=3, textvariable=hour_var)
            hour_spinbox.grid(row=0, column=2, padx=5)
            
            ttk.Label(date_frame, text=":").grid(row=0, column=3)
            
            # 分钟选择
            minute_var = IntVar(value=due_date.minute)
            minute_spinbox = ttk.Spinbox(date_frame, from_=0, to=59, width=3, textvariable=minute_var)
            minute_spinbox.grid(row=0, column=4, padx=5)
            
            # 作业描述
            ttk.Label(dialog, text="assignment description:").grid(row=2, column=0, padx=10, pady=10, sticky="nw")
            description_text = Text(dialog, width=40, height=10)
            description_text.grid(row=2, column=1, padx=10, pady=10, sticky="nw")
            # 确保assignment_content属性存在
            if hasattr(selected_assignment, 'assignment_content'):
                description_text.insert("1.0", selected_assignment.assignment_content)
            
            # 按钮框架
            btn_frame = ttk.Frame(dialog)
            btn_frame.grid(row=3, column=0, columnspan=2, pady=20)
            
            # 保存按钮 - 修改回调函数以处理日期选择器的值
            def save_assignment():
                new_title = title_entry.get()
                
                if not new_title:
                    messagebox.showerror("error", "please fill in all required fields.")
                    return
                    
                try:
                    # 更新作业属性
                    selected_assignment.title = new_title
                    
                    # 获取日期和时间
                    selected_date = date_entry.get_date()
                    selected_hour = hour_var.get()
                    selected_minute = minute_var.get()
                    
                    # 组合成完整的日期时间
                    new_due_date = datetime(selected_date.year, selected_date.month, selected_date.day, 
                                          selected_hour, selected_minute)
                    selected_assignment.due_date = new_due_date
                    
                    # 更新作业内容
                    if hasattr(selected_assignment, 'assignment_content'):
                        selected_assignment.assignment_content = description_text.get("1.0", "end-1c")
                    
                    messagebox.showinfo("success", f"assignment '{new_title}' has been updated.")
                    dialog.destroy()
                    self._load_assignments_data()  # 刷新作业列表
                    self.lms.save_data()  # 保存数据
                except Exception as e:
                    messagebox.showerror("error", f"an error occurred while updating the assignment: {str(e)}")
                    
            save_btn = ttk.Button(btn_frame, text="save", width=10, command=save_assignment)
            save_btn.pack(side="left", padx=10)
            
            # 取消按钮
            cancel_btn = ttk.Button(btn_frame, text="cancel", width=10, command=dialog.destroy)
            cancel_btn.pack(side="left", padx=10)
        except Exception as e:
            messagebox.showerror("error", f"an error occurred while opening the edit dialog: {str(e)}")
        
    def _delete_assignment(self, item_id):
        """删除作业"""
        if messagebox.askyesno("confirm deletion", "are you sure you want to delete this assignment?"): 
            try:
                # 获取作业信息
                item = self.assignments_tree.item(item_id)
                if not item or not item["values"]:
                    messagebox.showerror("error", "unable to retrieve assignment information.")
                    return
                    
                # 假设第一个值是课程名称,第二个是作业标题
                if len(item["values"]) >= 2:
                    course_name = item["values"][0]
                    assignment_title = item["values"][1]
                else:
                    messagebox.showerror("error", "assignment information format is incorrect.")
                    return
                
                # 查找对应的课程和作业对象
                selected_course = None
                for course in self.current_user.managed_courses:
                    if course.course_name.lower() == course_name.lower():
                        selected_course = course
                        break
                        
                if not selected_course:
                    messagebox.showerror("error", f"course '{course_name}' not found.")
                    return
                    
                selected_assignment = None
                for assignment in selected_course.course_assignments:
                    if assignment.title.lower() == assignment_title.lower():
                        selected_assignment = assignment
                        break
                        
                if not selected_assignment:
                    messagebox.showerror("error", f"assignment '{assignment_title}' not found.")
                    return
                    
                # 调用Course的remove_assignment方法
                if selected_course.remove_assignment(selected_assignment):
                    # 同时从教师的created_assignments中移除
                    if hasattr(self.current_user, 'created_assignments') and selected_assignment in self.current_user.created_assignments:
                        self.current_user.created_assignments.remove(selected_assignment)
                        
                    self.assignments_tree.delete(item_id)
                    messagebox.showinfo("success", f"assignment '{assignment_title}' has been deleted.")
                    self.lms.save_data()  # 保存数据
                else:
                    messagebox.showerror("error", f"failed to delete assignment '{assignment_title}'.")
            except Exception as e:
                messagebox.showerror("error", f"an error occurred while deleting the assignment: {str(e)}")
    
    def _add_admin_menu(self, parent):
        """添加管理员菜单"""
        menu_items = [
            ("dashboard", self.show_dashboard),
            ("user management", self.show_user_management),
            ("course approval", self.show_course_approval),
            ("system statistics", self.show_system_stats),
            ("profile", self.show_profile)
        ]
        
        self._add_menu_items(parent, menu_items)
    
    def _add_menu_items(self, parent, menu_items):
        """添加菜单项到侧边栏"""
        for text, command in menu_items:
            button = ttk.Button(parent, text=text, style="TButton", command=command)
            button.pack(fill="x", pady=5, padx=10)

    def show_course_approval(self):
        """显示课程审核界面(管理员)"""
        if not isinstance(self.current_user, Administrator):
            return

        self._clear_content_panel()

        # 页面标题
        title_label = ttk.Label(self.content_panel, text="course approval", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)

        # 创建课程列表框架
        courses_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        courses_frame.pack(fill="both", expand=True, pady=10, padx=10)

        # 创建表格
        columns = ("course_id", "course_name", "teacher", "description", "max_students")
        tree = ttk.Treeview(courses_frame, columns=columns, show="headings", style="Custom.Treeview")

        # 定义列宽和标题
        tree.column("course_id", width=100, anchor="center")
        tree.column("course_name", width=150, anchor="w")
        tree.column("teacher", width=100, anchor="center")
        tree.column("description", width=300, anchor="w")
        tree.column("max_students", width=80, anchor="center")

        tree.heading("course_id", text="course id")
        tree.heading("course_name", text="course name")
        tree.heading("teacher", text="teacher")
        tree.heading("description", text="description")
        tree.heading("max_students", text="max students")

        # 添加滚动条
        scrollbar = ttk.Scrollbar(courses_frame, orient="vertical", command=tree.yview)
        tree.configure(yscroll=scrollbar.set)

        # 放置表格和滚动条
        tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # 获取所有待审核的课程
        pending_courses = []
        for course in self.lms.courses:
            if course.status == "pending":
                pending_courses.append(course)

        # 添加数据到表格
        for course in pending_courses:
            teacher_name = "unknown"
            # 查找创建课程的教师
            for teacher in self.lms.teachers:
                if course in teacher.managed_courses:
                    teacher_name = teacher.username
                    break
            
            tree.insert("", tk.END, values=(
                course.course_id,
                course.course_name,
                teacher_name,
                course.course_description,
                course.max_students
            ))

        # 添加操作按钮
        bottom_frame = ttk.Frame(self.content_panel)
        bottom_frame.pack(fill="x", pady=10, padx=10)

        def approve_course():
            selected_item = tree.selection()
            if not selected_item:
                messagebox.showinfo("info", "please select a course first.")
                return

            item = tree.item(selected_item)
            course_id = item["values"][0]
            course_name = item["values"][1]

            # 查找对应的课程对象
            for course in pending_courses:
                if course.course_id == course_id:
                    try:
                        # 尝试审核课程
                        result = self.current_user.approve_course(course)
                        
                        # 确保课程状态被正确设置为已审核
                        course.status = "approved"
                        
                        # 确保课程在系统课程列表中
                        if course not in self.lms.courses:
                            self.lms.courses.append(course)
                        
                        # 确保课程在教师的管理课程列表中
                        for teacher in self.lms.teachers:
                            if course in teacher.managed_courses:
                                # 确保教师知道课程已通过审核
                                # 这里可以添加通知逻辑或其他处理
                                break
                        
                        # 强制保存数据
                        self.lms._data_changed = True  # 标记数据已更改
                        self.lms.save_data(force=True)  # 强制保存
                        
                        messagebox.showinfo("success", f"course '{course_name}' has been approved.")
                        self.show_course_approval()  # 刷新列表
                    except Exception as e:
                        messagebox.showerror("error", f"an error occurred during approval: {str(e)}")
                    break

        def reject_course():
            selected_item = tree.selection()
            if not selected_item:
                messagebox.showinfo("info", "please select a course first.")    
                return

            item = tree.item(selected_item)
            course_id = item["values"][0]
            course_name = item["values"][1]

            # 确认拒绝
            if messagebox.askyesno("confirm reject", f"are you sure you want to reject course '{course_name}'?"):
                # 查找对应的课程对象
                for course in pending_courses:
                    if course.course_id == course_id:
                        # 移除课程
                        if course in self.lms.courses:
                            self.lms.courses.remove(course)
                        # 从创建教师的管理课程中移除
                        for teacher in self.lms.teachers:
                            if course in teacher.managed_courses:
                                teacher.managed_courses.remove(course)
                                break
                        self.lms.save_data()
                        messagebox.showinfo("success", f"course '{course_name}' has been rejected.")
                        self.show_course_approval()  # 刷新列表
                        break

        approve_button = ttk.Button(bottom_frame, text="approve", style="Primary.TButton", command=approve_course)
        approve_button.pack(side="left", padx=(0, 10))

        reject_button = ttk.Button(bottom_frame, text="reject", style="Secondary.TButton", command=reject_course)   
        reject_button.pack(side="left")
    
    def show_system_stats(self):
        """显示系统统计信息(管理员)"""
        if not isinstance(self.current_user, Administrator):
            return

        self._clear_content_panel()

        # 页面标题
        title_label = ttk.Label(self.content_panel, text="system statistics", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)

        # 创建统计信息框架
        stats_frame = ttk.Frame(self.content_panel, padding=20, style="Card.TFrame")
        stats_frame.pack(fill="both", expand=True, pady=10, padx=10)

        # 创建统计卡片网格
        grid_frame = ttk.Frame(stats_frame)
        grid_frame.pack(fill="both", expand=True)

        # 统计数据
        total_students = len(self.lms.students)
        total_teachers = len(self.lms.teachers)
        total_courses = len(self.lms.courses)
        total_assignments = 0
        for course in self.lms.courses:
            total_assignments += len(course.course_assignments)
        
        # 已完成作业数量
        completed_assignments = 0
        for student in self.lms.students:
            completed_assignments += len(student.submitted_assignments)
        
        # 创建统计卡片
        stats = [
            ("total students", total_students, "#3498db"),  # 蓝色
            ("total teachers", total_teachers, "#2ecc71"),  # 绿色
            ("total courses", total_courses, "#e74c3c"),  # 红色
            ("total assignments", total_assignments, "#f39c12"),  # 橙色
            ("completed assignments", completed_assignments, "#9b59b6"),  # 紫色
            ("assignment completion rate", f"{completed_assignments/total_assignments*100:.1f}%" if total_assignments > 0 else "0.0%", "#1abc9c")  # 青色
        ]

        # 放置统计卡片
        for i, (title, value, color) in enumerate(stats):
            # 创建卡片框架
            card_frame = ttk.Frame(grid_frame, padding=15, style="Card.TFrame")
            card_frame.grid(row=i//2, column=i%2, sticky="nsew", padx=10, pady=10)
            
            # 设置网格权重使卡片均匀分布
            grid_frame.grid_columnconfigure(i%2, weight=1)
            grid_frame.grid_rowconfigure(i//2, weight=1)
            
            # 标题标签
            title_label = ttk.Label(card_frame, text=title, style="Subheading.TLabel")
            title_label.pack(anchor="w")
            
            # 值标签
            value_label = ttk.Label(card_frame, text=str(value), font=("Arial", 24, "bold"), foreground=color)
            value_label.pack(anchor="w", pady=10)

        # 添加系统信息区域
        system_info_frame = ttk.Frame(self.content_panel, padding=15, style="Card.TFrame")
        system_info_frame.pack(fill="x", pady=10, padx=10)

        # 系统信息标签
        info_title = ttk.Label(system_info_frame, text="system information", style="Subheading.TLabel")
        info_title.pack(anchor="w", pady=(0, 10))

        # 系统版本
        version_label = ttk.Label(system_info_frame, text=f"system version: {SYSTEM_VERSION}")
        version_label.pack(anchor="w", pady=5)
        
        # 数据文件位置
        data_file_label = ttk.Label(system_info_frame, text=f"data file: {self.lms.data_file}")
        data_file_label.pack(anchor="w", pady=5)
        
        # 最后备份时间(尝试获取)
        last_backup = "no backup yet"
        try:
            import os
            import json
            if hasattr(self.lms, 'last_backup_time'):
                last_backup = self.lms.last_backup_time
            elif os.path.exists('data.json'):
                # 尝试从数据文件中读取最后备份时间
                try:
                    with open('data.json', 'r') as f:
                        data = json.load(f)
                        if 'last_backup' in data:
                            last_backup = data['last_backup']
                except:
                    pass
        except:
            pass
        
        backup_label = ttk.Label(system_info_frame, text=f"last backup time: {last_backup}")
        backup_label.pack(anchor="w", pady=5)

        # 当前时间
        import datetime
        current_time_label = ttk.Label(system_info_frame, text=f"current time: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")    
        current_time_label.pack(anchor="w", pady=5)

        # 添加刷新按钮
        bottom_frame = ttk.Frame(self.content_panel)
        bottom_frame.pack(fill="x", pady=10, padx=10)

        refresh_button = ttk.Button(bottom_frame, text="refresh stats", style="Primary.TButton", command=self.show_system_stats)
        refresh_button.pack(side="left")

    def show_grade_assignment(self):
        """显示成绩评定界面"""
        if not isinstance(self.current_user, Teacher):
            messagebox.showerror("permission error", "only teachers can grade assignments")
            return
        
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="grade assignments", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建课程选择框架
        course_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        course_frame.pack(fill="x", pady=10, padx=10)
        
        course_label = ttk.Label(course_frame, text="select course:")
        course_label.pack(anchor="w", pady=5)
        
        # 获取教师管理的课程
        managed_courses = self.current_user.managed_courses
        
        if not managed_courses:
            no_courses_label = ttk.Label(course_frame, text="you are not managing any courses")
            no_courses_label.pack(pady=10)
            return
        
        # 创建课程下拉菜单
        course_var = tk.StringVar()
        course_combobox = ttk.Combobox(course_frame, textvariable=course_var, state="readonly", width=50)
        
        # 填充课程选项
        course_options = []
        course_map = {}
        
        for i, course in enumerate(managed_courses, 1):
            option_text = f"{course.course_name} (ID: {course.course_id})"
            course_options.append(option_text)
            course_map[option_text] = course
        
        course_combobox['values'] = course_options
        if course_options:
            course_combobox.current(0)
        
        course_combobox.pack(fill="x", pady=5)
        
        # 创建作业选择区域
        assignment_frame = ttk.LabelFrame(self.content_panel, text="select assignment", padding=10)
        assignment_frame.pack(fill="x", pady=10, padx=10)
        
        assignment_label = ttk.Label(assignment_frame, text="select assignment:")
        assignment_label.pack(anchor="w", pady=5)
        
        assignment_var = tk.StringVar()
        assignment_combobox = ttk.Combobox(assignment_frame, textvariable=assignment_var, state="disabled", width=50)
        assignment_combobox.pack(fill="x", pady=5)
        
        # 创建成绩评定区域
        grading_frame = ttk.LabelFrame(self.content_panel, text="grade assignments", padding=10)
        grading_frame.pack(fill="both", expand=True, pady=10, padx=10)
        
        # 创建学生表格
        columns = ("student_id", "student_name", "submission_status", "score")
        tree = ttk.Treeview(grading_frame, columns=columns, show="headings", style="Custom.Treeview")
        
        tree.column("student_id", width=100, anchor="center")
        tree.column("student_name", width=150, anchor="w")
        tree.column("submission_status", width=100, anchor="center")
        tree.column("score", width=80, anchor="center")
        
        tree.heading("student_id", text="student id")
        tree.heading("student_name", text="student name")
        tree.heading("submission_status", text="submission status")
        tree.heading("score", text="score")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(grading_frame, orient="vertical", command=tree.yview)
        tree.configure(yscroll=scrollbar.set)
        
        # 放置表格和滚动条
        tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 评分按钮
        score_button = ttk.Button(grading_frame, text="grade", style="Primary.TButton", state="disabled")
        score_button.pack(pady=10)
        
        # 添加选择事件处理函数 - 修复评分按钮无法点击的问题
        def on_tree_select(event):
            selected_items = tree.selection()
            if selected_items:
                # 检查选中的学生是否已提交作业
                selected_item = selected_items[0]
                item = tree.item(selected_item)
                submission_status = item["values"][2]
                # 同时接受英文和中文状态值
                if submission_status in ("submitted", "submitted"):
                    score_button.config(state="normal")
                else:
                    score_button.config(state="disabled")
            else:
                score_button.config(state="disabled")
        
        # 绑定表格选择事件
        tree.bind("<<TreeviewSelect>>", on_tree_select)
        
        # 评分函数 - 定义在使用之前
        def grade_student():
            selected_items = tree.selection()
            if not selected_items:
                messagebox.showinfo("info", "please select a student")
                return
            
            selected_item = selected_items[0]
            item = tree.item(selected_item)
            student_id = item["values"][0]
            student_name = item["values"][1]
            submission_status = item["values"][2]
            
            if submission_status != "submitted":
                messagebox.showinfo("info", f"{student_name} has not submitted the assignment yet")
                return
            
            # 获取当前选择的作业
            selected_course_text = course_var.get()
            selected_assignment_text = assignment_var.get()
            
            if not selected_course_text or not hasattr(assignment_combobox, 'assignment_map') or not selected_assignment_text:
                return
            
            selected_course = course_map[selected_course_text]
            selected_assignment = assignment_combobox.assignment_map[selected_assignment_text]
            
            # 尝试获取当前成绩
            current_score = selected_assignment.submissions.get(student_id, {}).get("score", "")
            
            # 创建评分对话框
            score_window = tk.Toplevel(self.root)
            score_window.title("Grade Assignment")
            score_window.geometry("400x300")
            score_window.resizable(False, False)
            
            # 居中显示
            score_window.geometry(f"+{self.root.winfo_x()+150}+{self.root.winfo_y()+100}")
            
            # 评分标签
            score_label = ttk.Label(score_window, text=f"grade {student_name}:")
            score_label.pack(pady=10)

            # 显示学生提交的作业内容
            if student_id in selected_assignment.submissions:
                submission_content = selected_assignment.submissions[student_id].get("content", "")
                content_label = ttk.Label(score_window, text="assignment content:")
                content_label.pack(pady=(5, 0), anchor="w", padx=20)
    
                content_text = tk.Text(score_window, height=10, width=50, wrap=tk.WORD)
                content_text.pack(pady=5, padx=20, fill="both", expand=True)
                content_text.insert(tk.END, submission_content)
                content_text.config(state=tk.DISABLED)
            
            # 评分输入框
            score_var = tk.StringVar(value=str(current_score) if current_score else "")
            score_entry = ttk.Entry(score_window, textvariable=score_var, width=10)
            score_entry.pack(pady=10)
            
            # 保存评分函数
            def save_score():
                from Assignment_and_Grading.system_modules import GradingSystem
                try:
                    score = float(score_var.get())
                    if score < 0 or score > 100:
                        messagebox.showerror("error", "score must be between 0 and 100")
                        return
                    
                   
                    # grading_system = GradingSystem(self.lms)
                    # grading_system.grade_assignment(
                    #     student_id=student_id,
                    #     course_id=selected_course.course_id,
                    #     assignment_id=selected_assignment.assignment_id,
                    #     score=score
                    # )

                    grading_system = GradingSystem(self.lms)
                    grading_system.grade_assignment_by_ids(
                        student_id=student_id,
                        course_id=selected_course.course_id,
                        assignment_id=selected_assignment.assignment_id,
                        score=score
                    )
                    
                    # 更新作业的submissions字典
                    if not hasattr(selected_assignment, 'submissions'):
                        selected_assignment.submissions = {}
                    if student_id not in selected_assignment.submissions:
                        selected_assignment.submissions[student_id] = {}
                    selected_assignment.submissions[student_id]["score"] = score
                    selected_assignment.submissions[student_id]["graded_time"] = datetime.now()
                    selected_assignment.submissions[student_id]["status"] = "graded"  
                    
                    # 保存数据
                    self.lms.mark_data_changed()
                    if self.lms.save_data():
                        update_students()

                        score_window.destroy()
                        messagebox.showinfo("info", f"graded {student_name}: {score}")
                    else:
                        messagebox.showerror("error", "save data failed")
                except ValueError:
                    messagebox.showerror("error", "please enter a valid score")
            
            # 保存按钮
            save_button = ttk.Button(score_window, text="grade", style="Primary.TButton", command=save_score)
            save_button.pack(pady=10)
        
        # 将grade_student函数绑定到评分按钮 - 现在grade_student已经定义
        score_button.config(command=grade_student)
        
        # 更新作业列表的函数
        def update_assignments(*args):
            selected_course_text = course_var.get()
            if not selected_course_text:
                return
            
            selected_course = course_map[selected_course_text]
            
            # 检查课程是否有作业
            if hasattr(selected_course, 'course_assignments') and selected_course.course_assignments:
                assignment_options = []
                assignment_map = {}
                
                for i, assignment in enumerate(selected_course.course_assignments, 1):
                    option_text = f"{assignment.title} (deadline: {assignment.due_date})"
                    assignment_options.append(option_text)
                    assignment_map[option_text] = assignment
                
                assignment_combobox['values'] = assignment_options
                assignment_combobox.configure(state="readonly")
                if assignment_options:
                    assignment_combobox.current(0)
                
                # 更新assignment_map全局变量
                assignment_combobox.assignment_map = assignment_map
                update_students()
            else:
                assignment_combobox.configure(state="disabled")
                assignment_combobox.set("")
                tree.delete(*tree.get_children())
                messagebox.showinfo("info", "this course has no assignments")
        
        # 更新学生列表的函数
        def update_students(*args):
            selected_course_text = course_var.get()
            selected_assignment_text = assignment_var.get()
            
            if not selected_course_text or not hasattr(assignment_combobox, 'assignment_map') or not selected_assignment_text:
                return
            
            try:
                selected_course = course_map[selected_course_text]
                selected_assignment = assignment_combobox.assignment_map[selected_assignment_text]
            
                # 清空表格
                tree.delete(*tree.get_children())
            
                # 获取课程中的学生
                enrolled_students = []
                added_student_ids = set()
                for user in User.all_users():
                    if isinstance(user, Student) and user.student_id not in added_student_ids:
                        for course in user.enrolled_courses:
                            if course.course_id == selected_course.course_id:
                                enrolled_students.append(user)
                                added_student_ids.add(user.student_id)
                                break
            
                # 添加学生到表格
                for student in enrolled_students:
                    # 安全地获取提交状态,避免NoneType错误
                    # 安全地获取提交状态,避免NoneType错误
                    submission_status = "not submitted"
                    score_text = "not graded"
                    
                    # 检查selected_assignment是否有submissions属性且不为None
                    if hasattr(selected_assignment, 'submissions') and selected_assignment.submissions is not None:
                        if isinstance(selected_assignment.submissions, dict):
                            if student.student_id in selected_assignment.submissions:
                                student_submission = selected_assignment.submissions[student.student_id]
                                if isinstance(student_submission, dict):
                                    # 检查提交状态
                                    raw_status = student_submission.get("status", "submitted")
                                    if raw_status.lower() in ["submitted", "已提交"]:
                                        submission_status = "submitted"
                                    elif raw_status.lower() in ["graded", "已评分"]:
                                        submission_status = "graded"
                                    else:
                                        submission_status = "not submitted"
                                    # 获取分数
                                    score = student_submission.get("score", None)
                                    if score is None:
                                        score_text = "not graded"
                                    else:
                                        try:
                                            score_float = float(score)
                                            score_text = f"{score_float:.2f}"
                                        except (ValueError, TypeError):
                                            score_text = str(score) if score != "" else "not graded"
                    tree.insert("", tk.END, values=(student.student_id, student.username, submission_status, score_text))
            except Exception as e:
                print(f"update students error: {str(e)}")
                messagebox.showerror("error", f"update students error: {str(e)}")
        
        # 评分函数
        def grade_student():
            selected_items = tree.selection()
            if not selected_items:
                messagebox.showinfo("info", "please select a student")
                return
            
            selected_item = selected_items[0]
            item = tree.item(selected_item)
            student_id = item["values"][0]
            student_name = item["values"][1]
            submission_status = item["values"][2]
            
            if submission_status not in ["submitted", "已提交"]:
                messagebox.showinfo("info", f"{student_name} has not submitted this assignment")
                return
            
            # 获取当前选择的作业
            selected_course_text = course_var.get()
            selected_assignment_text = assignment_var.get()
            
            if not selected_course_text or not hasattr(assignment_combobox, 'assignment_map') or not selected_assignment_text:
                return
            
            selected_course = course_map[selected_course_text]
            selected_assignment = assignment_combobox.assignment_map[selected_assignment_text]
            
            # 尝试获取当前成绩
            current_score = selected_assignment.submissions.get(student_id, {}).get("score", "")
            
            # 创建评分对话框
            score_window = tk.Toplevel(self.root)
            score_window.title("Grade Assignment")
            score_window.geometry("400x300")
            score_window.resizable(False, False)
            
            # 居中显示
            score_window.geometry(f"+{self.root.winfo_x()+150}+{self.root.winfo_y()+100}")
            
            # 评分标签
            score_label = ttk.Label(score_window, text=f"grade {student_name}:")
            score_label.pack(pady=10)

            # 显示学生提交的作业内容
            if student_id in selected_assignment.submissions:
                submission_content = selected_assignment.submissions[student_id].get("content", "")
                content_label = ttk.Label(score_window, text="submission content:")
                content_label.pack(pady=(5, 0), anchor="w", padx=20)
    
                content_text = tk.Text(score_window, height=10, width=50, wrap=tk.WORD)
                content_text.pack(pady=5, padx=20, fill="both", expand=True)
                content_text.insert(tk.END, submission_content)
                content_text.config(state=tk.DISABLED)
            
            # 评分输入框
            score_var = tk.StringVar(value=str(current_score) if current_score else "")
            score_entry = ttk.Entry(score_window, textvariable=score_var, width=10)
            score_entry.pack(pady=10)
            
            # 保存评分函数
            def save_score():
                from Assignment_and_Grading.system_modules import GradingSystem
                try:
                    score = float(score_var.get())
                    if score < 0 or score > 100:
                        messagebox.showerror("error", "score must be between 0 and 100")
                        return
                    
                    # 使用GradingSystem进行评分
                    grading_system = GradingSystem(self.lms)
                    grading_system.grade_assignment_by_ids(
                        student_id=student_id,
                        course_id=selected_course.course_id,
                        assignment_id=selected_assignment.assignment_id,
                        score=score
                    )
                    # GradingSystem.grade_assignment_by_ids(
                    #     student_id=student_id,
                    #     course_id=selected_course.course_id,
                    #     assignment_id=selected_assignment.assignment_id,
                    #     score=score
                    # )
                    
                    # 更新作业的submissions字典
                    if hasattr(selected_assignment, 'submissions') and selected_assignment.submissions:
                        if student_id not in selected_assignment.submissions:
                            selected_assignment.submissions[student_id] = {}
                        selected_assignment.submissions[student_id]["score"] = score
                    
                    
                    # 刷新学生列表
                    update_students()
                    
                    # 关闭对话框
                    score_window.destroy()
                    messagebox.showinfo("info", f"grade {student_name}: {score}")
                    
                except ValueError:
                    messagebox.showerror("error", "please enter a valid score")
            
            # 保存按钮
            save_button = ttk.Button(score_window, text="grade", style="Primary.TButton", command=save_score)
            save_button.pack(pady=10)
        
        # 绑定事件
        course_var.trace_add("write", update_assignments)
        assignment_var.trace_add("write", update_students)
        score_button.configure(command=grade_student)
        
        # 初始加载作业列表
        if course_options:
            update_assignments()

    def show_my_assignments(self):
        """显示学生的作业列表并提供提交功能"""
        if not isinstance(self.current_user, Student):
            return

        self._clear_content_panel()

        # 页面标题
        title_label = ttk.Label(self.content_panel, text="my assignments", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)

        # 创建作业列表框架
        assignments_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        assignments_frame.pack(fill="both", expand=True, pady=10, padx=10)

        # 创建表格
        columns = ("course_name", "assignment_title", "due_date", "status", "action")
        tree = ttk.Treeview(assignments_frame, columns=columns, show="headings", style="Custom.Treeview")

        # 定义列宽和标题
        tree.column("course_name", width=150, anchor="w")
        tree.column("assignment_title", width=200, anchor="w")
        tree.column("due_date", width=150, anchor="center")
        tree.column("status", width=80, anchor="center")
        tree.column("action", width=80, anchor="center")

        tree.heading("course_name", text="course name")
        tree.heading("assignment_title", text="assignment title")
        tree.heading("due_date", text="due date")
        tree.heading("status", text="status")
        tree.heading("action", text="action")

        # 添加滚动条
        scrollbar = ttk.Scrollbar(assignments_frame, orient="vertical", command=tree.yview)
        tree.configure(yscroll=scrollbar.set)

        # 放置表格和滚动条
        tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")

        # 获取学生已选课程的所有作业
        all_assignments = []
        for course in self.current_user.enrolled_courses:
            if hasattr(course, 'course_assignments'):
                for assignment in course.course_assignments:
                    # 修改:改进检查作业是否已提交的逻辑
                    is_submitted = False
                    assignment_id = getattr(assignment, 'assignment_id', getattr(assignment, 'assignable_id', None))
                
                    # 确保assignment_id存在
                    if assignment_id:
                        # 方法1: 直接检查student的submitted_assignments
                        for submission_dict in self.current_user.submitted_assignments:
                            # 直接使用assignment_id进行匹配
                            if submission_dict.get("assignment_id") == assignment_id:
                                # 检查状态是否为提交状态(考虑中英文两种可能)
                                status_val = submission_dict.get("status", "")
                                if status_val.lower() in ["submitted", "已提交"]:
                                    is_submitted = True
                                    break
                    
                        # 方法2: 同时检查assignment对象的submissions
                        if not is_submitted and hasattr(assignment, 'submissions'):
                            student_id = self.current_user.student_id
                            if student_id in assignment.submissions:
                                submission_status = assignment.submissions[student_id].get("status", "")
                                if submission_status.lower() in ["submitted", "已提交"]:
                                    is_submitted = True

                    status = "submitted" if is_submitted else "unsubmitted"
                    all_assignments.append((course, assignment, status))

        # 添加数据到表格
        for course, assignment, status in all_assignments:
            due_date_str = assignment.due_date.strftime('%Y-%m-%d %H:%M') if hasattr(assignment, 'due_date') else ""
            # 修改:使用正确的属性名作为标签
            assignment_id = getattr(assignment, 'assignment_id', getattr(assignment, 'assignable_id', None))
            tree.insert("", tk.END, values=(course.course_name, assignment.title, due_date_str, status, "submit"), tags=(assignment_id,))

        # 添加提交作业的功能
        def on_submit_assignment(event):
            selected_item = tree.selection()
            if not selected_item:
                messagebox.showinfo("info", "please select an assignment to submit")
                return
            item = tree.item(selected_item)
            assignment_id = item["tags"][0]

            target_assignment = None
            for course, assignment, _ in all_assignments:
                if getattr(assignment, 'assignment_id', getattr(assignment, 'assignable_id', None)) == assignment_id:
                    target_assignment = assignment
                    break

            if target_assignment:
                # 创建提交对话框
                submit_window = tk.Toplevel(self.root)
                submit_window.title(f"submit assignment: {target_assignment.title}")
                submit_window.geometry("600x450")
                submit_window.transient(self.root)
                submit_window.grab_set()
                submit_window.resizable(True, True)
                
                # 设置提交窗口的图标和样式
                if hasattr(self.root, 'iconbitmap') and self.root.iconbitmap():
                    submit_window.iconbitmap(self.root.iconbitmap())
        
                 # 作业信息框架
                info_frame = ttk.Frame(submit_window, padding=10)
                info_frame.pack(fill="x")
        
                # 创建信息标签网格
                info_grid = ttk.Frame(info_frame)
                info_grid.pack(fill="x")
        
                ttk.Label(info_grid, text="course:", width=10).grid(row=0, column=0, sticky="w", pady=2)
                ttk.Label(info_grid, text=target_assignment.course.course_name).grid(row=0, column=1, sticky="w", pady=2)
        
                ttk.Label(info_grid, text="assignment title:", width=10).grid(row=1, column=0, sticky="w", pady=2)
                ttk.Label(info_grid, text=target_assignment.title).grid(row=1, column=1, sticky="w", pady=2)
        
                # 显示截止日期并计算剩余时间
                due_date_str = target_assignment.due_date.strftime("%Y-%m-%d %H:%M")
                ttk.Label(info_grid, text="due date:", width=10).grid(row=2, column=0, sticky="w", pady=2)
        
                # 计算剩余时间
                now = datetime.datetime.now()
                time_left = target_assignment.due_date - now
                if time_left.total_seconds() > 0:
                    days_left = time_left.days
                    hours_left, remainder = divmod(time_left.seconds, 3600)
                    minutes_left, _ = divmod(remainder, 60)
                    time_left_str = f"{days_left} days {hours_left} hours {minutes_left} minutes left"
                    due_date_label = ttk.Label(info_grid, text=f"{due_date_str} ({time_left_str})")
                else:
                    due_date_label = ttk.Label(info_grid, text=f"{due_date_str} (expired)", foreground="red")
                due_date_label.grid(row=2, column=1, sticky="w", pady=2)
        
                # 提交内容框架
                content_frame = ttk.Frame(submit_window, padding=10)
                content_frame.pack(fill="both", expand=True)
                
                ttk.Label(content_frame, text="submit content:").pack(anchor="w")
                text_widget = tk.Text(content_frame, wrap=tk.WORD, height=12, undo=True)
                text_widget.pack(fill="both", expand=True, pady=5)
        
                # 添加滚动条
                text_scrollbar = ttk.Scrollbar(text_widget, orient="vertical", command=text_widget.yview)
                text_widget.config(yscrollcommand=text_scrollbar.set)
                text_scrollbar.pack(side="right", fill="y")
        
                # 提交按钮框架
                button_frame = ttk.Frame(submit_window, padding=10)
                button_frame.pack(fill="x", side="bottom")
        
                def do_submit():
                    """提交作业的核心逻辑"""
                    content = text_widget.get(1.0, tk.END).strip()
                    if not content:
                        messagebox.showerror("error", "submit content cannot be empty")
                        return
            
                    # 检查是否已经提交过
                    assignment_id = getattr(target_assignment, 'assignment_id', getattr(target_assignment, 'assignable_id', None))
                    already_submitted = False
                    for submitted in self.current_user.submitted_assignments:
                        if submitted["assignment_id"] == assignment_id:
                            already_submitted = True
                            break
            
                    if already_submitted:
                        if messagebox.askyesno("confirm", "you have already submitted this assignment, do you want to override?"):
                            # 允许覆盖提交
                            pass
                        else:
                            return
            
                    # 提交作业
                    try:
                        success, msg = self.current_user.submit_assignment(target_assignment, content)
                
                        if success:
                            # 确保作业提交状态正确保存到assignment对象
                            if not hasattr(target_assignment, 'submissions'):
                                target_assignment.submissions = {}
                            
                            # 创建提交记录
                            submission_record = {
                                "content": content,
                                "submit_time": datetime.datetime.now(),
                                "is_late": datetime.datetime.now() > target_assignment.due_date,
                                "status": "submitted",
                                "score": None
                            }
                            
                            # 保存到作业对象
                            target_assignment.submissions[self.current_user.student_id] = submission_record
                    
                            # 保存数据并添加错误处理
                            try:
                                save_result = self.lms.save_data(force=True)
                                if not save_result:
                                    messagebox.showwarning("warning", "assignment submitted but data save may be incomplete, please check logs")
                                else:
                                    # 更新进度
                                    if isinstance(self.current_user, Student):
                                        self.current_user.update_course_progress(target_assignment.course.course_id)
                            
                                    # 刷新作业列表
                                    self.show_my_assignments()
                                    messagebox.showinfo("success", msg)
                                    submit_window.destroy()
                            except Exception as e:
                                print(f"save data error: {e}")
                                messagebox.showerror("error", f"assignment submitted but data save failed: {str(e)}")
                        else:
                            messagebox.showerror("error", msg)
                    except Exception as e:
                        print(f"submit assignment error: {e}")
                        messagebox.showerror("error", f"submit process error: {str(e)}")
        
                # 绑定提交和取消按钮
                ttk.Button(button_frame, text="submit", style="Primary.TButton", command=do_submit).pack(side="right", padx=(0, 10))
                ttk.Button(button_frame, text="cancel", command=submit_window.destroy).pack(side="right")
        
                # 为文本框添加快捷键支持
                text_widget.bind("<Control-a>", lambda e: text_widget.tag_add("sel", "1.0", "end"))
                text_widget.bind("<Control-z>", lambda e: text_widget.event_generate("<<Undo>>"))
                text_widget.bind("<Control-y>", lambda e: text_widget.event_generate("<<Redo>>"))
        
                # 设置文本框自动获取焦点
                text_widget.focus_set()

        # 绑定双击事件到提交功能
        tree.bind("<Double-1>", on_submit_assignment)
    
        # 添加右键菜单支持
        def on_right_click(event):
            item = tree.identify_row(event.y)
            if item:
                tree.selection_set(item)
                popup_menu = tk.Menu(self.root, tearoff=0)
                popup_menu.add_command(label="submit assignment", command=lambda: on_submit_assignment(None))
                popup_menu.post(event.x_root, event.y_root)
    
        tree.bind("<Button-3>", on_right_click)

    def show_student_submissions(self):
        """显示学生作业提交列表供教师查看和批改"""
        if not isinstance(self.current_user, Teacher):
            messagebox.showinfo("info", "only teacher can view student assignment submissions")
            return
        
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="student assignment submissions", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建筛选框架
        filter_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        filter_frame.pack(fill="x", pady=10, padx=10)
        
        # 课程筛选
        ttk.Label(filter_frame, text="select course: ").grid(row=0, column=0, sticky="w", padx=5, pady=5)
        course_var = tk.StringVar()
        course_combo = ttk.Combobox(filter_frame, textvariable=course_var, state="readonly", width=30)
        
        # 添加课程选项
        course_values = []
        self.course_map = {}
        for course in self.current_user.managed_courses:
            course_values.append(course.course_name)
            self.course_map[course.course_name] = course
        
        course_combo['values'] = course_values
        if course_values:
            course_combo.current(0)
        course_combo.grid(row=0, column=1, padx=5, pady=5)
        
        # 作业筛选
        ttk.Label(filter_frame, text="select assignment: ").grid(row=0, column=2, sticky="w", padx=5, pady=5)
        assignment_var = tk.StringVar()
        assignment_combo = ttk.Combobox(filter_frame, textvariable=assignment_var, state="readonly", width=30)
        assignment_combo.grid(row=0, column=3, padx=5, pady=5)
        
        # 状态筛选
        ttk.Label(filter_frame, text="filter status: ").grid(row=0, column=4, sticky="w", padx=5, pady=5)
        status_var = tk.StringVar(value="all")
        status_combo = ttk.Combobox(filter_frame, textvariable=status_var, state="readonly", width=15)
        status_combo['values'] = ("all", "unscored", "scored", "late")
        status_combo.grid(row=0, column=5, padx=5, pady=5)
        
        # 刷新按钮
        refresh_button = ttk.Button(filter_frame, text="refresh list", command=lambda: load_submission_data())
        refresh_button.grid(row=0, column=6, padx=10, pady=5)
        
        # 设置列权重让界面更灵活
        filter_frame.columnconfigure(1, weight=1)
        filter_frame.columnconfigure(3, weight=1)
        filter_frame.columnconfigure(6, weight=2)
        
        # 创建提交列表框架
        submission_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        submission_frame.pack(fill="both", expand=True, pady=10, padx=10)
        
        # 创建表格
        columns = ("student_id", "student_name", "submit_time", "status", "score", "action")
        tree = ttk.Treeview(submission_frame, columns=columns, show="headings", style="Custom.Treeview")
        
        # 定义列宽和标题
        tree.column("student_id", width=120, anchor="center")
        tree.column("student_name", width=150, anchor="w")
        tree.column("submit_time", width=180, anchor="center")
        tree.column("status", width=100, anchor="center")
        tree.column("score", width=80, anchor="center")
        tree.column("action", width=100, anchor="center")
        
        tree.heading("student_id", text="student id")
        tree.heading("student_name", text="student name")
        tree.heading("submit_time", text="submit time")
        tree.heading("status", text="status")
        tree.heading("score", text="score")
        tree.heading("action", text="action")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(submission_frame, orient="vertical", command=tree.yview)
        tree.configure(yscroll=scrollbar.set)
        
        # 放置表格和滚动条
        tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 加载提交数据
        def load_submission_data():
            # 清空表格
            for item in tree.get_children():
                tree.delete(item)
                
            # 获取筛选条件
            selected_course_name = course_var.get()
            selected_assignment_title = assignment_var.get()
            selected_status = status_var.get()
            
            # 验证筛选条件
            if not selected_course_name or selected_course_name not in self.course_map:
                return
            
            selected_course = self.course_map[selected_course_name]
            
            # 更新作业下拉列表
            assignment_values = []
            self.assignment_map = {}
            
            # 获取该课程的所有作业
            if hasattr(selected_course, 'course_assignments'):
                course_assignments = selected_course.course_assignments
            elif hasattr(selected_course, 'assignments'):
                course_assignments = selected_course.assignments
            else:
                course_assignments = []
                
            for assignment in course_assignments:
                assignment_values.append(assignment.title)
                self.assignment_map[assignment.title] = assignment
                
            assignment_combo['values'] = assignment_values
            if assignment_values and not selected_assignment_title:
                assignment_combo.current(0)
                selected_assignment_title = assignment_values[0]
            
            # 如果未选择作业,不显示数据
            if not selected_assignment_title or selected_assignment_title not in self.assignment_map:
                return
            
            selected_assignment = self.assignment_map[selected_assignment_title]
            
            # 获取所有提交记录
            submissions = getattr(selected_assignment, 'submissions', {})
            
            # 遍历提交记录
            for student_id, submission in submissions.items():
                # 查找对应的学生对象
                student = None
                for s in selected_course.enrolled_students:
                    if getattr(s, 'student_id', None) == student_id or getattr(s, 'user_id', None) == student_id:
                        student = s
                        break
                
                if not student:
                    continue
                
                # 格式化提交时间
                submit_time = submission.get("submit_time", datetime.datetime.now())
                if isinstance(submit_time, str):
                    try:
                        submit_time_obj = datetime.datetime.fromisoformat(submit_time.replace('Z', '+00:00'))
                        submit_time_str = submit_time_obj.strftime('%Y-%m-%d %H:%M:%S')
                    except:
                        submit_time_str = "invalid time"
                else:
                    submit_time_str = submit_time.strftime('%Y-%m-%d %H:%M:%S')
                
                # 确定状态
                is_late = submission.get("is_late", False)
                score = submission.get("score", None)
                
                if score is not None:
                    status = "scored"
                else:
                    status = "unscored"
                    
                if is_late:
                    status += " (late)"
                
                # 应用状态筛选
                if selected_status != "all":
                    if selected_status == "unscored" and score is not None:
                        continue
                    if selected_status == "scored" and score is None:
                        continue
                    if selected_status == "late" and not is_late:
                        continue
                
                # 显示分数
                score_str = f"{score:.2f}" if score is not None else "-"
                
                # 添加到表格
                tree.insert("", tk.END, values=(
                    student_id,
                    student.username,
                    submit_time_str,
                    status,
                    score_str,
                    "view"
                ), tags=(student_id, selected_assignment.assignment_id))
        
        # 处理课程选择变化
        def on_course_selected(event):
            # 清空作业选择
            assignment_var.set("")
            assignment_combo['values'] = []
            # 清空表格
            for item in tree.get_children():
                tree.delete(item)
            
        course_combo.bind("<<ComboboxSelected>>", on_course_selected)
        
        # 处理作业选择变化
        assignment_combo.bind("<<ComboboxSelected>>", lambda event: load_submission_data())
        status_combo.bind("<<ComboboxSelected>>", lambda event: load_submission_data())
        
        # 双击查看或批改作业
        def on_view_submission(event):
            selected_item = tree.selection()
            if not selected_item:
                return
            
            item = tree.item(selected_item)
            student_id = item["tags"][0]
            assignment_id = item["tags"][1]
            
            # 查找学生和作业对象
            student = None
            assignment = None
            selected_course = self.course_map.get(course_var.get(), None)
            
            if selected_course:
                for s in selected_course.enrolled_students:
                    if getattr(s, 'student_id', None) == student_id or getattr(s, 'user_id', None) == student_id:
                        student = s
                        break
                
                if hasattr(selected_course, 'course_assignments'):
                    for a in selected_course.course_assignments:
                        if getattr(a, 'assignment_id', None) == assignment_id:
                            assignment = a
                            break
            
            if not student or not assignment:
                messagebox.showerror("Error", "Failed to find the student or assignment.")
                return
            
            # 获取提交内容
            submission = assignment.submissions.get(student_id, {})
            content = submission.get("content", "")
            score = submission.get("score", None)
            is_late = submission.get("is_late", False)
            
            # 创建查看/批改窗口
            review_window = tk.Toplevel(self.root)
            review_window.title(f"View/Grade Assignment - {assignment.title} (Student: {student.username})")
            review_window.geometry("700x550")
            review_window.transient(self.root)
            review_window.grab_set()
            review_window.resizable(True, True)
            
            # 学生和作业信息框架
            info_frame = ttk.Frame(review_window, padding=10)
            info_frame.pack(fill="x")
            
            info_grid = ttk.Frame(info_frame)
            info_grid.pack(fill="x")
            
            ttk.Label(info_grid, text="Student:", width=10).grid(row=0, column=0, sticky="w", pady=2)
            ttk.Label(info_grid, text=f"{student.username} ({student_id})").grid(row=0, column=1, sticky="w", pady=2)
            
            ttk.Label(info_grid, text="Submit Time:", width=10).grid(row=1, column=0, sticky="w", pady=2)
            
            submit_time = submission.get("submit_time", datetime.datetime.now())
            if isinstance(submit_time, str):
                try:
                    submit_time_obj = datetime.datetime.fromisoformat(submit_time.replace('Z', '+00:00'))
                    submit_time_str = submit_time_obj.strftime('%Y-%m-%d %H:%M:%S')
                except:
                    submit_time_str = submit_time
            else:
                submit_time_str = submit_time.strftime('%Y-%m-%d %H:%M:%S')
            
            submit_time_label = ttk.Label(info_grid, text=submit_time_str)
            if is_late:
                submit_time_label.config(foreground="red")
            submit_time_label.grid(row=1, column=1, sticky="w", pady=2)
            
            # 截止日期信息
            ttk.Label(info_grid, text="deadline:", width=10).grid(row=1, column=2, sticky="w", pady=2, padx=(20, 0))
            ttk.Label(info_grid, text=assignment.due_date.strftime('%Y-%m-%d %H:%M:%S')).grid(row=1, column=3, sticky="w", pady=2)
            
            # 作业内容框架
            content_frame = ttk.Frame(review_window, padding=10)
            content_frame.pack(fill="both", expand=True)
            
            ttk.Label(content_frame, text="Assignment Content:").pack(anchor="w")
            content_text = tk.Text(content_frame, wrap=tk.WORD, height=15)
            content_text.insert(tk.END, content)
            content_text.config(state="disabled")  # 只读
            content_text.pack(fill="both", expand=True, pady=5)
            
            # 添加内容滚动条
            content_scrollbar = ttk.Scrollbar(content_text, orient="vertical", command=content_text.yview)
            content_text.config(yscrollcommand=content_scrollbar.set)
            content_scrollbar.pack(side="right", fill="y")
            
            # 评分框架
            grade_frame = ttk.Frame(review_window, padding=10)
            grade_frame.pack(fill="x")
            
            ttk.Label(grade_frame, text="Grade: ").pack(side="left", padx=(0, 10))
            score_var = tk.StringVar(value=str(score) if score is not None else "")
            score_entry = ttk.Entry(grade_frame, textvariable=score_var, width=10)
            score_entry.pack(side="left", padx=(0, 5))
            ttk.Label(grade_frame, text=f"/ {assignment.total_points}").pack(side="left")
            
            # 评语框架
            comment_frame = ttk.Frame(review_window, padding=10)
            comment_frame.pack(fill="x")
            
            ttk.Label(comment_frame, text="Comment: ").pack(anchor="w")
            comment_text = tk.Text(comment_frame, wrap=tk.WORD, height=5)
            comment_text.pack(fill="x", pady=5)
            
            # 按钮框架
            button_frame = ttk.Frame(review_window, padding=10)
            button_frame.pack(fill="x", side="bottom")
            
            def save_grade():
                try:
                    # 验证分数
                    score_str = score_var.get().strip()
                    if not score_str:
                        messagebox.showerror("Error", "Please enter a score")
                        return
                    
                    try:
                        score_value = float(score_str)
                        if score_value < 0 or score_value > assignment.total_points:
                            raise ValueError(f"Grade must be between 0 and {assignment.total_points}")
                    except ValueError as e:
                        messagebox.showerror("Error", f"Invalid grade: {str(e)}")
                        return
                    
                    # 保存分数
                    success = self.current_user.grade_assignment(assignment, student, score_value)
                    
                    if success:
                        # 更新作业对象中的提交记录
                        submission["score"] = score_value
                        submission["comment"] = comment_text.get(1.0, tk.END).strip()
                        submission["graded_time"] = datetime.datetime.now()
                        submission["graded_by"] = self.current_user.teacher_id
                        
                        # 保存数据
                        try:
                            self.lms.save_data(force=True)
                            messagebox.showinfo("Success", "Grade saved")
                            review_window.destroy()
                            load_submission_data()  # 刷新列表
                        except Exception as e:
                            messagebox.showerror("Error", f"Error saving data: {str(e)}")
                    else:
                        messagebox.showerror("Error", "Failed to save grade")
                except Exception as e:
                    print(f"Error grading assignment: {e}")
                    messagebox.showerror("Error", f"Error grading assignment: {str(e)}")
            
            # 绑定按钮
            ttk.Button(button_frame, text="Save Grade", style="Primary.TButton", command=save_grade).pack(side="right", padx=(0, 10))
            ttk.Button(button_frame, text="Close", command=review_window.destroy).pack(side="right")
            
        # 绑定双击事件
        tree.bind("<Double-1>", on_view_submission)
        
        # 初始加载数据
        if course_values:
            load_submission_data()

    def show_dashboard(self):
        """显示用户仪表盘"""
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="Dashboard", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建信息卡片容器
        cards_frame = ttk.Frame(self.content_panel)
        cards_frame.pack(fill="x", pady=10, padx=10)
        
        # 显示用户信息卡片
        user_info_frame = ttk.Frame(cards_frame, padding=10, style="Card.TFrame")
        user_info_frame.pack(fill="x", pady=(0, 10))
        
        user_title = ttk.Label(user_info_frame, text="User Information", style="Subheading.TLabel")
        user_title.pack(anchor="w", pady=(0, 5))
        
        info_text = f"Username: {self.current_user.username}\n"
        info_text += f"Role: {self._get_role_text()}\n"
        info_text += f"Email: {self.current_user.email}\n"
        
        if isinstance(self.current_user, Student):
            info_text += f"Student ID: {self.current_user.student_id}\n"
            info_text += f"Enrolled Courses: {len(self.current_user.enrolled_courses)}"
        elif isinstance(self.current_user, Teacher):
            info_text += f"Teacher ID: {self.current_user.teacher_id}\n"
            info_text += f"Managed Courses: {len(self.current_user.managed_courses)}"
        elif isinstance(self.current_user, Administrator):
            info_text += f"Admin ID: {self.current_user.admin_id}\n"
            info_text += f"System Users: {len(self.current_user.system_users)}"
        
        info_label = ttk.Label(user_info_frame, text=info_text, justify="left")
        info_label.pack(anchor="w")
        
        # 显示活动日志卡片
        activity_frame = ttk.Frame(cards_frame, padding=10, style="Card.TFrame")
        activity_frame.pack(fill="both", expand=True, pady=(10, 0))
        
        activity_title = ttk.Label(activity_frame, text="Recent Activities", style="Subheading.TLabel")
        activity_title.pack(anchor="w", pady=(0, 5))
        
        # 创建活动列表
        activity_listbox = tk.Listbox(activity_frame, width=80, height=10)
        activity_listbox.pack(fill="both", expand=True, side="left", padx=(0, 5))
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(activity_frame, orient="vertical", command=activity_listbox.yview)
        scrollbar.pack(side="right", fill="y")
        activity_listbox.config(yscrollcommand=scrollbar.set)
        
        # 模拟活动数据
        activities = []
        
        if isinstance(self.current_user, Student):
            activities = [
                "LoggedIn - " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "Viewed Course Grades - 2025-10-25 09:30:45",
                "Enrolled in New Course - 2025-10-24 14:20:15",
                "Completed Assignment Submission - 2025-10-23 16:45:30",
                "Updated Personal Information - 2025-10-20 11:15:00"
            ]
        elif isinstance(self.current_user, Teacher):
            activities = [
                "LoggedIn - " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "Created New Course - 2025-10-24 10:15:20",
                "Completed Assignment Grading - 2025-10-23 15:30:45",
                "Viewed Class Roster - 2025-10-22 14:10:15",
                "Published New Assignment - 2025-10-20 09:45:00"
            ]
        elif isinstance(self.current_user, Administrator):
            activities = [
                "LoggedIn - " + datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "Added New User - 2025-10-25 14:20:30",
                "Approved New Course - 2025-10-24 10:15:20",
                "Viewed System Statistics - 2025-10-23 09:30:15",
                "Backed Up System Data - 2025-10-20 16:45:00"
            ]
        
        # 添加活动到列表
        for activity in activities:
            activity_listbox.insert(tk.END, activity)
    
    def _clear_content_panel(self):
        """清空内容面板"""
        for widget in self.content_panel.winfo_children():
            widget.destroy()
    
    def show_my_courses(self):
        """显示学生的已选课程"""
        if not isinstance(self.current_user, Student):
            return
        
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="My Enrolled Courses", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建课程列表框架
        courses_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        courses_frame.pack(fill="both", expand=True, pady=10, padx=10)
        
        # 创建表格
        columns = ("course_id", "course_name", "teacher", "description", "students")
        tree = ttk.Treeview(courses_frame, columns=columns, show="headings", style="Custom.Treeview")
        
        # 定义列宽和标题
        tree.column("course_id", width=100, anchor="center")
        tree.column("course_name", width=150, anchor="w")
        tree.column("teacher", width=100, anchor="center")
        tree.column("description", width=300, anchor="w")
        tree.column("students", width=80, anchor="center")
        
        tree.heading("course_id", text="Course ID")
        tree.heading("course_name", text="Course Name")
        tree.heading("teacher", text="Teacher")
        tree.heading("description", text="Course Description")
        tree.heading("students", text="Enrolled Students")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(courses_frame, orient="vertical", command=tree.yview)
        tree.configure(yscroll=scrollbar.set)
        
        # 放置表格和滚动条
        tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 添加数据到表格
        for course in self.current_user.enrolled_courses:
            teacher_name = course.teacher.username if course.teacher else "未分配"
            tree.insert("", tk.END, values=(
                course.course_id,
                course.course_name,
                teacher_name,
                course.course_description,
                f"{len(course.enrolled_students)}/{course.max_students}"
            ))
        
        # 添加查看进度按钮
        bottom_frame = ttk.Frame(self.content_panel)
        bottom_frame.pack(fill="x", pady=10, padx=10)
        
        def view_progress():
            selected_item = tree.selection()
            if not selected_item:
                messagebox.showinfo("info", "Please select a course to view progress.")
                return
            
            item = tree.item(selected_item)
            course_id = item["values"][0]
            
            # 查找对应的课程对象
            for course in self.current_user.enrolled_courses:
                if course.course_id == course_id:
                    # 显示课程进度对话框
                    progress_window = tk.Toplevel(self.root)
                    progress_window.title(f"Course Progress - {course.course_name}")
                    progress_window.geometry("500x400")
                    progress_window.transient(self.root)
                    progress_window.grab_set()
                    
                    # 计算进度
                    total_assignments = len(course.course_assignments)
                    submitted_count = 0
                    # 正确的做法:遍历学生已提交的作业,计算与当前课程匹配的数量
                    for submission in self.current_user.submitted_assignments:
                        if submission.get("course_id") == course.course_id:
                            submitted_count += 1
                    
                    progress = (submitted_count / total_assignments) * 100 if total_assignments > 0 else 0
                    
                    # 创建进度显示界面
                    progress_frame = ttk.Frame(progress_window, padding=20)
                    progress_frame.pack(fill="both", expand=True)
                    
                    title = ttk.Label(progress_frame, text=f"{course.course_name} Progress", style="Subheading.TLabel")
                    title.pack(pady=10)
                    
                    progress_label = ttk.Label(progress_frame, text=f"Completed Assignments: {submitted_count}/{total_assignments}")
                    progress_label.pack(pady=10)
                    
                    # 创建进度条
                    progress_var = tk.DoubleVar(value=progress)
                    progress_bar = ttk.Progressbar(progress_frame, variable=progress_var, length=400, mode="determinate")
                    progress_bar.pack(pady=20)
                    
                    percentage_label = ttk.Label(progress_frame, text=f"{progress:.1f}%")
                    percentage_label.pack(pady=10)
                    
                    # 关闭按钮
                    close_button = ttk.Button(progress_frame, text="Close", command=progress_window.destroy)
                    close_button.pack(pady=10)
                    
                    break
        
        progress_button = ttk.Button(bottom_frame, text="View Course Progress", style="Primary.TButton", command=view_progress)
        progress_button.pack(side="left", padx=(0, 10))
        
        # 添加退课按钮
        def drop_course():
            selected_item = tree.selection()
            if not selected_item:
                messagebox.showinfo("info", "Please select a course to drop.")
                return
            
            item = tree.item(selected_item)
            course_id = item["values"][0]
            course_name = item["values"][1]
            
            # 确认退课
            if messagebox.askyesno("Confirm Drop Course", f"Are you sure you want to drop '{course_name}'?"):
                # 查找对应的课程对象
                for course in self.current_user.enrolled_courses:
                    if course.course_id == course_id:
                        if self.current_user.drop_course(course):
                            messagebox.showinfo("Success", f"Successfully dropped '{course_name}'")
                            # 刷新课程列表
                            self.show_my_courses()
                            # 添加以下代码保存数据
                            self.lms.save_data()
                        else:
                            messagebox.showerror("Error", "Failed to drop course. Please try again.")
                        break
        
        drop_button = ttk.Button(bottom_frame, text="Drop Course", style="Secondary.TButton", command=drop_course)
        drop_button.pack(side="left")
    
    def show_grades(self):
        """显示学生的成绩信息"""
        if not isinstance(self.current_user, Student):
            return
        
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="Grades Query", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建成绩列表框架
        grades_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        grades_frame.pack(fill="both", expand=True, pady=10, padx=10)
        
        # 创建表格
        columns = ("course_id", "course_name", "final_grade", "status")
        tree = ttk.Treeview(grades_frame, columns=columns, show="headings", style="Custom.Treeview")
        
        # 定义列宽和标题
        tree.column("course_id", width=100, anchor="center")
        tree.column("course_name", width=200, anchor="w")
        tree.column("final_grade", width=100, anchor="center")
        tree.column("status", width=100, anchor="center")
        
        tree.heading("course_id", text="Course ID")
        tree.heading("course_name", text="Course Name")
        tree.heading("final_grade", text="Final Grade")
        tree.heading("status", text="Grade Status")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(grades_frame, orient="vertical", command=tree.yview)
        tree.configure(yscroll=scrollbar.set)
        
        # 放置表格和滚动条
        tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 添加数据到表格
        total_grade = 0
        grade_count = 0
        
        # 修改:确保显示所有已注册课程,即使grades字典为空
        for course in self.current_user.enrolled_courses:
            # 从grades字典获取成绩,如果不存在则默认为0
            grade = self.current_user.grades.get(course, 0)
            total_grade += grade
            grade_count += 1
            
            # 判断成绩状态
            if grade >= 60:
                status = "Pass"
            else:
                status = "Fail"
            
            tree.insert("", tk.END, values=(
                course.course_id,
                course.course_name,
                f"{grade:.2f}",
                status
            ))
        
        # 显示平均成绩
        if grade_count > 0:
            avg_grade = total_grade / grade_count
            avg_label = ttk.Label(self.content_panel, text=f"Average Grade: {avg_grade:.2f}", style="Subheading.TLabel")
            avg_label.pack(pady=10, padx=10, anchor="w")
        
        # 添加查看详细成绩按钮
        bottom_frame = ttk.Frame(self.content_panel)
        bottom_frame.pack(fill="x", pady=10, padx=10)
        
        def view_details():
            selected_item = tree.selection()
            if not selected_item:
                messagebox.showinfo("Info", "Please select a course to view details.")
                return
            
            # 获取选中的课程ID
            item = selected_item[0]
            course_id = tree.item(item, "values")[0]
            
            # 查找对应的课程对象
            selected_course = None
            for course in self.current_user.enrolled_courses:
                if course.course_id == course_id:
                    selected_course = course
                    break
            
            if not selected_course:
                messagebox.showerror("Error", "Course not found.")
                return
            
            # 创建详细成绩对话框
            details_window = tk.Toplevel(self.root)
            details_window.title(f"Grade Details - {selected_course.course_name}")
            details_window.geometry("500x400")
            details_window.configure(bg="#f0f0f0")
            
            # 创建标题
            title_label = ttk.Label(details_window, text=f"Assignments for {selected_course.course_name}", style="Heading.TLabel")
            title_label.pack(fill="x", pady=10, padx=10)
            
            # 创建作业列表
            assignments_frame = ttk.Frame(details_window, padding=10, style="Card.TFrame")
            assignments_frame.pack(fill="both", expand=True, pady=10, padx=10)
            
            # 创建列表框显示作业成绩
            listbox = tk.Listbox(assignments_frame, font=(".AppleSystemUIFont", 12), selectbackground="#a6a6a6", selectforeground="white")
            listbox.pack(side="left", fill="both", expand=True)
            
            # 添加滚动条
            scrollbar = ttk.Scrollbar(assignments_frame, orient="vertical", command=listbox.yview)
            scrollbar.pack(side="right", fill="y")
            listbox.config(yscrollcommand=scrollbar.set)
            
            # 检查是否有作业成绩
            has_assignments = False
            displayed_assignments = set()  # 用于去重
            
            # 第一步:处理学生submitted_assignments中的作业
            for submission in self.current_user.submitted_assignments:
                assignment_id = submission["assignment_id"]
                if assignment_id in displayed_assignments:
                    continue
                displayed_assignments.add(assignment_id)
                
                # 查找对应的作业对象
                assignment_obj = None
                for assign in selected_course.course_assignments:
                    if hasattr(assign, 'assignment_id') and assign.assignment_id == assignment_id:
                        assignment_obj = assign
                        break
                
                if assignment_obj:
                    has_assignments = True
                    # 优先从assignment_obj.submissions获取成绩
                    score = None
                    if hasattr(assignment_obj, 'submissions') and self.current_user.student_id in assignment_obj.submissions:
                        score = assignment_obj.submissions[self.current_user.student_id].get('score', None)
                    # 如果没有,从submission获取
                    if score is None:
                        score = submission.get('score', None)
                    
                    # 格式化提交时间
                    submit_time = submission.get('submit_time')
                    if isinstance(submit_time, datetime):
                        submit_time_str = submit_time.strftime("%Y-%m-%d %H:%M:%S")
                    else:
                        try:
                            # 尝试解析字符串时间
                            submit_time_str = datetime.fromisoformat(submit_time).strftime("%Y-%m-%d %H:%M:%S")
                        except:
                            submit_time_str = str(submit_time)
                    
                    # 显示作业信息
                    score_str = f"{score:.2f}" if score is not None else "Not Graded"
                    listbox.insert(tk.END, f"Assignment: {assignment_obj.title}")
                    listbox.insert(tk.END, f"  Submit Time: {submit_time_str}")
                    listbox.insert(tk.END, f"  Score: {score_str}")
                    listbox.insert(tk.END, "")  # 空行分隔
            
            # 第二步:处理课程中但学生未提交的作业
            for assignment in selected_course.course_assignments:
                assignment_id = getattr(assignment, 'assignment_id', None)
                if assignment_id and assignment_id not in displayed_assignments:
                    displayed_assignments.add(assignment_id)
                    has_assignments = True
                    
                    # 检查作业对象的submissions中是否有该学生的成绩
                    score = None
                    if hasattr(assignment, 'submissions') and self.current_user.student_id in assignment.submissions:
                        score = assignment.submissions[self.current_user.student_id].get('score', None)
                    
                    score_str = f"{score:.2f}" if score is not None else "Not Submitted"
                    listbox.insert(tk.END, f"Assignment: {assignment.title}")
                    listbox.insert(tk.END, f"  Status: {score_str}")
                    listbox.insert(tk.END, "")  # 空行分隔
            
            # 如果没有作业成绩,显示提示
            if not has_assignments:
                listbox.insert(tk.END, "No assignment grades available yet.")
            
            # 添加关闭按钮
            details_button = ttk.Button(details_window, text="Close", style="Primary.TButton", command=details_window.destroy)
            details_button.pack(pady=10)
        
        details_button = ttk.Button(bottom_frame, text="View Details", style="Primary.TButton", command=view_details)
        details_button.pack(side="left")
    
    def show_enroll_courses(self):
        """显示选课界面"""
        if not isinstance(self.current_user, Student):
            return
        
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="Enroll Courses", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建可选课程列表框架
        courses_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        courses_frame.pack(fill="both", expand=True, pady=10, padx=10)
        
        # 创建表格
        columns = ("course_id", "course_name", "teacher", "description", "status")
        tree = ttk.Treeview(courses_frame, columns=columns, show="headings", style="Custom.Treeview")
        
        # 定义列宽和标题
        tree.column("course_id", width=100, anchor="center")
        tree.column("course_name", width=150, anchor="w")
        tree.column("teacher", width=100, anchor="center")
        tree.column("description", width=300, anchor="w")
        tree.column("status", width=80, anchor="center")
        
        tree.heading("course_id", text="Course ID")
        tree.heading("course_name", text="Course Name")
        tree.heading("teacher", text="Teacher")
        tree.heading("description", text="Course Description")
        tree.heading("status", text="Status")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(courses_frame, orient="vertical", command=tree.yview)
        tree.configure(yscroll=scrollbar.set)
        
        # 放置表格和滚动条
        tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 获取所有课程并过滤已选课程
        all_courses = self.lms.courses
        enrolled_course_ids = [course.course_id for course in self.current_user.enrolled_courses]
        
        # 添加数据到表格
        for course in all_courses:
            # 跳过已选课程
            if course.course_id in enrolled_course_ids:
                continue
            
            # 检查课程状态和人数
            if course.status != "approved":
                status = "Not Approved"
            elif len(course.enrolled_students) >= course.max_students:
                status = "Full"
            else:
                status = "Available"
            
            teacher_name = course.teacher.username if course.teacher else "Unassigned"
            
            # 如果课程可选,则添加到列表
            tree.insert("", tk.END, values=(
                course.course_id,
                course.course_name,
                teacher_name,
                course.course_description,
                status
            ))
        
        # 添加选课按钮
        bottom_frame = ttk.Frame(self.content_panel)
        bottom_frame.pack(fill="x", pady=10, padx=10)
        
        def enroll_selected_course():
            selected_item = tree.selection()
            if not selected_item:
                messagebox.showinfo("提示", "Please select a course first")
                return
            
            item = tree.item(selected_item)
            course_id = item["values"][0]
            course_name = item["values"][1]
            status = item["values"][4]
            
            # 检查课程状态
            if status != "Available":
                messagebox.showinfo("info", f"{course_name} is not available for enrollment")
                return
            
            # 确认选课
            if messagebox.askyesno("Confirm Enrollment", f"Are you sure you want to enroll in '{course_name}'?"):
                # 查找对应的课程对象
                for course in all_courses:
                    if course.course_id == course_id:
                        if self.current_user.enroll_course(course):
                            messagebox.showinfo("Success", f"Successfully enrolled in '{course_name}'")
                            # 刷新选课列表
                            self.show_enroll_courses()
                        else:
                            messagebox.showerror("Error", "Enrollment failed, please try again")
                        break
        
        enroll_button = ttk.Button(bottom_frame, text="Enroll", style="Primary.TButton", command=enroll_selected_course)
        enroll_button.pack(side="left")
    
    def show_profile(self):
        """显示个人信息"""
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="User Profile", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建个人信息框架
        profile_frame = ttk.Frame(self.content_panel, padding=20, style="Card.TFrame")
        profile_frame.pack(fill="x", pady=10, padx=10)
        
        # 创建表单
        form_frame = ttk.Frame(profile_frame)
        form_frame.pack(fill="x")
        
        # 用户名
        ttk.Label(form_frame, text="Username: ").grid(row=0, column=0, sticky="w", pady=5, padx=10)
        ttk.Label(form_frame, text=self.current_user.username).grid(row=0, column=1, sticky="w", pady=5, padx=10)
        
        # 角色
        ttk.Label(form_frame, text="Role: ").grid(row=1, column=0, sticky="w", pady=5, padx=10)
        ttk.Label(form_frame, text=self._get_role_text()).grid(row=1, column=1, sticky="w", pady=5, padx=10)
        
        # 邮箱
        ttk.Label(form_frame, text="Email: ").grid(row=2, column=0, sticky="w", pady=5, padx=10)
        email_var = tk.StringVar(value=self.current_user.email)
        email_entry = ttk.Entry(form_frame, textvariable=email_var)
        email_entry.grid(row=2, column=1, sticky="ew", pady=5, padx=10)
        
        # 用户ID
        id_label = "User ID: "
        id_value = self.current_user.user_id
        
        if isinstance(self.current_user, Student):
            id_label = "Student ID: "
            id_value = self.current_user.student_id
        elif isinstance(self.current_user, Teacher):
            id_label = "Teacher ID: "
            id_value = self.current_user.teacher_id
        elif isinstance(self.current_user, Administrator):
            id_label = "Administrator ID: "
            id_value = self.current_user.admin_id
        
        ttk.Label(form_frame, text=id_label).grid(row=3, column=0, sticky="w", pady=5, padx=10)
        ttk.Label(form_frame, text=id_value).grid(row=3, column=1, sticky="w", pady=5, padx=10)
        
        # 设置列权重,让输入框可以伸展
        form_frame.columnconfigure(1, weight=1)
        
        # 添加修改按钮
        bottom_frame = ttk.Frame(profile_frame)
        bottom_frame.pack(fill="x", pady=10)
        
        def update_profile():
            new_email = email_var.get().strip()
            
            if not new_email:
                messagebox.showerror("Error", "Email cannot be empty")
                return
            
            # 更新个人信息
            try:
                self.current_user.update_profile({"email": new_email})
                messagebox.showinfo("Success", "Profile updated successfully")
                self.lms.save_data()
            except Exception as e:
                messagebox.showerror("Error", f"Update failed: {str(e)}")
        
        def change_password():
            # 创建修改密码对话框
            password_window = tk.Toplevel(self.root)
            password_window.title("Change Password")
            password_window.geometry("350x250")
            password_window.transient(self.root)
            password_window.grab_set()
            
            # 创建密码表单
            password_frame = ttk.Frame(password_window, padding=20)
            password_frame.pack(fill="both", expand=True)
            
            # 当前密码
            ttk.Label(password_frame, text="Current Password: ").grid(row=0, column=0, sticky="w", pady=5, padx=10)
            current_password_entry = ttk.Entry(password_frame, show="*")
            current_password_entry.grid(row=0, column=1, sticky="ew", pady=5, padx=10)
            
            # 新密码
            ttk.Label(password_frame, text="New Password: ").grid(row=1, column=0, sticky="w", pady=5, padx=10)
            new_password_entry = ttk.Entry(password_frame, show="*")
            new_password_entry.grid(row=1, column=1, sticky="ew", pady=5, padx=10)
            
            # 确认新密码
            ttk.Label(password_frame, text="Confirm New Password: ").grid(row=2, column=0, sticky="w", pady=5, padx=10)
            confirm_password_entry = ttk.Entry(password_frame, show="*")
            confirm_password_entry.grid(row=2, column=1, sticky="ew", pady=5, padx=10)
            
            # 设置列权重
            password_frame.columnconfigure(1, weight=1)
            
            # 按钮框架
            buttons_frame = ttk.Frame(password_frame)
            buttons_frame.grid(row=3, column=0, columnspan=2, pady=10)
            
            def handle_change_password():
                current_password = current_password_entry.get().strip()
                new_password = new_password_entry.get().strip()
                confirm_password = confirm_password_entry.get().strip()
                
                # 验证输入
                if not all([current_password, new_password, confirm_password]):
                    messagebox.showerror("Error", "Please fill in all password fields")
                    return
                
                if new_password != confirm_password:
                    messagebox.showerror("Error", "New passwords do not match") 
                    return
                
                # 尝试修改密码
                if self.current_user.change_password(current_password, new_password):
                    messagebox.showinfo("Success", "Password changed successfully")         
                    self.lms.save_data()
                    password_window.destroy()
                else:
                    messagebox.showerror("Error", "Current password is incorrect")
            
            # 确认按钮
            confirm_button = ttk.Button(buttons_frame, text="Confirm", style="Primary.TButton", command=handle_change_password)
            confirm_button.pack(side="left", padx=(0, 10))
            
            # 取消按钮
            cancel_button = ttk.Button(buttons_frame, text="Cancel", command=password_window.destroy)
            cancel_button.pack(side="left")
        
        update_button = ttk.Button(bottom_frame, text="Update Profile", style="Primary.TButton", command=update_profile)
        update_button.pack(side="left", padx=(0, 10))
        
        password_button = ttk.Button(bottom_frame, text="Change Password", style="Accent.TButton", command=change_password)
        password_button.pack(side="left")
    
    def show_managed_courses(self):
        """显示教师管理的课程"""
        if not isinstance(self.current_user, Teacher):
            return
        
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="My Managed Courses", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建课程列表框架
        courses_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        courses_frame.pack(fill="both", expand=True, pady=10, padx=10)
        
        # 创建表格
        columns = ("course_id", "course_name", "description", "students", "status")
        tree = ttk.Treeview(courses_frame, columns=columns, show="headings", style="Custom.Treeview")
        
        # 定义列宽和标题
        tree.column("course_id", width=100, anchor="center")
        tree.column("course_name", width=150, anchor="w")
        tree.column("description", width=300, anchor="w")
        tree.column("students", width=80, anchor="center")
        tree.column("status", width=80, anchor="center")
        
        tree.heading("course_id", text="Course ID")
        tree.heading("course_name", text="Course Name")
        tree.heading("description", text="Course Description")
        tree.heading("students", text="Enrolled Students")
        tree.heading("status", text="Status")
        
        # 添加滚动条
        scrollbar = ttk.Scrollbar(courses_frame, orient="vertical", command=tree.yview)
        tree.configure(yscroll=scrollbar.set)
        
        # 放置表格和滚动条
        tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 添加数据到表格
        for course in self.current_user.managed_courses:
            tree.insert("", tk.END, values=(
                course.course_id,
                course.course_name,
                course.course_description,
                f"{len(course.enrolled_students)}/{course.max_students}",
                "Approved" if course.status == "approved" else "Pending"
            ))                  
        
        # 添加创建课程按钮
        bottom_frame = ttk.Frame(self.content_panel)
        bottom_frame.pack(fill="x", pady=10, padx=10)
        
        def create_course():
            # 创建创建课程对话框
            create_window = tk.Toplevel(self.root)
            create_window.title("Create New Course")
            create_window.geometry("400x400")
            create_window.transient(self.root)
            create_window.grab_set()
            
            # 创建表单
            form_frame = ttk.Frame(create_window, padding=20)
            form_frame.pack(fill="both", expand=True)
            
            # 课程名称
            ttk.Label(form_frame, text="Course Name: ").grid(row=0, column=0, sticky="w", pady=5, padx=10)
            name_var = tk.StringVar()
            name_entry = ttk.Entry(form_frame, textvariable=name_var)
            name_entry.grid(row=0, column=1, sticky="ew", pady=5, padx=10)
            
            # 课程描述
            ttk.Label(form_frame, text="Course Description: ").grid(row=1, column=0, sticky="nw", pady=5, padx=10)
            desc_var = tk.StringVar()
            desc_text = tk.Text(form_frame, height=5, width=30)
            desc_text.grid(row=1, column=1, sticky="ew", pady=5, padx=10)
            
            # 最大学生数
            ttk.Label(form_frame, text="Max Students: ").grid(row=2, column=0, sticky="w", pady=5, padx=10)
            max_students_var = tk.StringVar(value="30")
            max_students_entry = ttk.Entry(form_frame, textvariable=max_students_var)
            max_students_entry.grid(row=2, column=1, sticky="ew", pady=5, padx=10)
            
            # 设置列权重
            form_frame.columnconfigure(1, weight=1)
            
            # 按钮框架
            buttons_frame = ttk.Frame(form_frame)
            buttons_frame.grid(row=3, column=0, columnspan=2, pady=10)
            
            def handle_create_course():
                name = name_var.get().strip()
                description = desc_text.get("1.0", tk.END).strip()
                max_students_str = max_students_var.get().strip()
                
                # 验证输入
                if not name:
                    messagebox.showerror("Error", "Course name cannot be empty")
                    return
                
                try:
                    max_students = int(max_students_str)
                    if max_students <= 0:
                        raise ValueError()
                except ValueError:
                    messagebox.showerror("Error", "Max students must be a positive integer")
                    return
                
                # 创建课程信息字典
                course_info = {
                    "name": name,
                    "desc": description,
                    "max_students": max_students
                }
                
                # 调用Teacher的create_course方法
                try:
                    new_course = self.current_user.create_course(course_info)
                    self.lms.save_data(force=True)
                    messagebox.showinfo("Success", f"Course '{name}' created successfully")
                    create_window.destroy()
                    self.show_managed_courses()  # 刷新课程列表
                except Exception as e:
                    messagebox.showerror("Error", f"Creation failed: {str(e)}")
            
            # 确认按钮
            confirm_button = ttk.Button(buttons_frame, text="Create", style="Primary.TButton", command=handle_create_course)
            confirm_button.pack(side="left", padx=(0, 10))
            
            # 取消按钮
            cancel_button = ttk.Button(buttons_frame, text="Cancel", command=create_window.destroy)
            cancel_button.pack(side="left")
        
        create_button = ttk.Button(bottom_frame, text="Create Course", style="Primary.TButton", command=create_course)
        create_button.pack(side="left", padx=(0, 10))
        
        # 添加修改课程按钮
        def modify_course():
            selected_item = tree.selection()
            if not selected_item:
                messagebox.showinfo("Info", "Please select a course to modify")
                return
            
            item = tree.item(selected_item)
            course_id = item["values"][0]
            course_name = item["values"][1]
            
            # 查找对应的课程对象
            course = None
            for c in self.current_user.managed_courses:
                if c.course_id == course_id:
                    course = c
                    break
            
            if not course:
                messagebox.showerror("Error", "Course not found")
                return
            
            # 创建修改课程对话框
            modify_window = tk.Toplevel(self.root)
            modify_window.title(f"Modify Course - {course_name}")
            modify_window.geometry("400x400")
            modify_window.transient(self.root)
            modify_window.grab_set()
            
            # 创建表单
            form_frame = ttk.Frame(modify_window, padding=20)
            form_frame.pack(fill="both", expand=True)
            
            # 课程名称
            ttk.Label(form_frame, text="Course Name: ").grid(row=0, column=0, sticky="w", pady=5, padx=10)
            name_var = tk.StringVar(value=course.course_name)
            name_entry = ttk.Entry(form_frame, textvariable=name_var)
            name_entry.grid(row=0, column=1, sticky="ew", pady=5, padx=10)
            
            # 课程描述
            ttk.Label(form_frame, text="Course Description: ").grid(row=1, column=0, sticky="nw", pady=5, padx=10)
            desc_text = tk.Text(form_frame, height=5, width=30)
            desc_text.insert(tk.END, course.course_description)
            desc_text.grid(row=1, column=1, sticky="ew", pady=5, padx=10)
            
            # 最大学生数
            ttk.Label(form_frame, text="Max Students: ").grid(row=2, column=0, sticky="w", pady=5, padx=10)
            max_students_var = tk.StringVar(value=str(course.max_students))
            max_students_entry = ttk.Entry(form_frame, textvariable=max_students_var)
            max_students_entry.grid(row=2, column=1, sticky="ew", pady=5, padx=10)
            
            # 设置列权重
            form_frame.columnconfigure(1, weight=1)
            
            # 按钮框架
            buttons_frame = ttk.Frame(form_frame)
            buttons_frame.grid(row=3, column=0, columnspan=2, pady=10)
            
            def handle_modify_course():
                name = name_var.get().strip()
                description = desc_text.get("1.0", tk.END).strip()
                max_students_str = max_students_var.get().strip()
                
                # 验证输入
                if not name:
                    messagebox.showerror("Error", "Course name cannot be empty")
                    return
                
                try:
                    max_students = int(max_students_str)
                    if max_students <= 0:
                        raise ValueError()
                except ValueError:
                    messagebox.showerror("Error", "Max students must be a positive integer")
                    return
                
                # 创建修改信息字典
                new_info = {
                    "name": name,
                    "desc": description,
                    "max_students": max_students
                }
                
                # 调用Teacher的modify_course方法
                if self.current_user.modify_course(course, new_info):
                    self.lms.save_data()
                    messagebox.showinfo("Success", "Course information updated")
                    modify_window.destroy()
                    self.show_managed_courses()  # 刷新课程列表
                else:
                    if course not in self.current_user.managed_courses:
                        messagebox.showerror("Error", "Modification failed: You do not have permission to modify this course")
                    else:
                        messagebox.showerror("Error", "Modification failed: Max students must be greater than or equal to the current number of students")
                    
            
            # 确认按钮
            confirm_button = ttk.Button(buttons_frame, text="Confirm", style="Primary.TButton", command=handle_modify_course)
            confirm_button.pack(side="left", padx=(0, 10))
            
            # 取消按钮
            cancel_button = ttk.Button(buttons_frame, text="Cancel", command=modify_window.destroy)
            cancel_button.pack(side="left")
        
        modify_button = ttk.Button(bottom_frame, text="Modify Course", style="Accent.TButton", command=modify_course)
        modify_button.pack(side="left", padx=(0, 10))
        
        # 添加删除课程按钮
        def delete_course():
            selected_item = tree.selection()
            if not selected_item:
                messagebox.showinfo("Info", "Please select a course to delete")
                return
            
            item = tree.item(selected_item)
            course_id = item["values"][0]
            course_name = item["values"][1]
            
            # 确认删除
            if messagebox.askyesno("Confirm Delete", f"Are you sure you want to delete course '{course_name}'?\nNote: This action cannot be undone."):
                # 查找对应的课程对象
                course = None
                for c in self.current_user.managed_courses:
                    if c.course_id == course_id:
                        course = c
                        break
                
                if not course:
                    messagebox.showerror("Error", "Course not found")
                    return
                
                # 调用Teacher的delete_course方法
                if self.current_user.delete_course(course):
                    if course in self.lms.courses:
                        self.lms.courses.remove(course)

                    self.lms.save_data()
                    messagebox.showinfo("Success", "Course deleted successfully")
                    self.show_managed_courses()  # 刷新课程列表
                else:
                    messagebox.showerror("Error", "Delete failed")
        
        delete_button = ttk.Button(bottom_frame, text="Delete Course", style="Secondary.TButton", command=delete_course)
        delete_button.pack(side="left")
    
    def show_class_roster(self):
        """显示班级花名册"""
        if not isinstance(self.current_user, Teacher):
            return
        
        self._clear_content_panel()
        
        # 页面标题
        title_label = ttk.Label(self.content_panel, text="Class Roster", style="Heading.TLabel")
        title_label.pack(fill="x", pady=10, padx=10)
        
        # 创建课程选择框架
        select_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        select_frame.pack(fill="x", pady=10, padx=10)
        
        ttk.Label(select_frame, text="Select Course: ").pack(side="left", padx=(0, 10))
        
        course_var = tk.StringVar()
        course_combo = ttk.Combobox(select_frame, textvariable=course_var, state="readonly")
        
        # 添加课程选项
        course_values = []
        self.course_map = {}
        
        for course in self.current_user.managed_courses:
            course_values.append(course.course_name)
            self.course_map[course.course_name] = course
        
        course_combo['values'] = course_values
        
        if course_values:
            course_combo.current(0)
        
        course_combo.pack(side="left", padx=(0, 10))
        
        # 创建花名册框架
        roster_frame = ttk.Frame(self.content_panel, padding=10, style="Card.TFrame")
        roster_frame.pack(fill="both", expand=True, pady=10, padx=10)
        
        # 初始化花名册表格
        columns = ("student_id", "username", "email")
        tree = ttk.Treeview(roster_frame, columns=columns, show="headings", style="Custom.Treeview")
        
        # 定义列宽和标题
        tree.column("student_id", width=120, anchor="center")
        tree.column("username", width=150, anchor="w")
        tree.column("email", width=300, anchor="w")
        
        tree.heading("student_id", text="Student ID")
        tree.heading("username", text="Username")
        tree.heading("email", text="Email")
        
         # 添加滚动条
        scrollbar = ttk.Scrollbar(roster_frame, orient="vertical", command=tree.yview)
        tree.configure(yscroll=scrollbar.set)
        
        # 放置表格和滚动条
        tree.pack(side="left", fill="both", expand=True)
        scrollbar.pack(side="right", fill="y")
        
        # 添加数据到表格
        def load_roster_data(event=None):
            # 清空表格
            for item in tree.get_children():
                tree.delete(item)
                
            # 获取选中的课程
            selected_course_name = course_var.get()
            if selected_course_name and selected_course_name in self.course_map:
                selected_course = self.course_map[selected_course_name]
                
                # 添加学生数据
                for student in selected_course.get_enrolled_students():
                    tree.insert("", tk.END, values=(
                        student.user_id,
                        student.username,
                        student.email
                    ))
        
        # 绑定课程选择事件
        course_combo.bind("<<ComboboxSelected>>", load_roster_data)
        
        # 初始加载数据
        if course_values:
            load_roster_data()

    def _setup_auto_save(self):
        def check_auto_save():
            if hasattr(self.lms, "check_auto_save"):
                self.lms.check_auto_save()

            self.root.after(60000, check_auto_save)  

        check_auto_save()

if __name__ == "__main__":
    app = GT_OOP_LMS_GUI()
